1.默认值
2.显示赋值
3.构造器赋值
4.对象名.属性名/对象名.方法名()
5.代码块赋值
{}
成员代码块/构造代码块
静态代码块 构造代码块/ 成员代码块: 位置: 类中方法外
作用: 给成员变量赋值
声明方式: {}
执行顺序: 先从上到下依次执行代码块 执行完毕再执行 构造器
一个类中可以存在多个代码块(先代码块后构造器)
注意:
1.创建几次对象 构造代码块就会执行几次 2.代码块有作用域限制 在代码块内声明的变量 只能在代码块内部使用 3.成员代码块可以使用静态资源
Debug调试
public class Person {
String name = "张三";
{
// name = "李四";
System.out.println("构造代码块1");
}
public Person() {
}
public Person(String name) {
this.name = name;
}
public void show(){
System.out.println("name =" + name);
}
{
System.out.println("构造代码块2");
}
}
public class Test {
public static void main(String[] args) {
Person person = new Person("李四");
System.out.println(person.name);
}
}
静态代码块:
位置: 类中方法外
声明: static {}
作用:给静态成员变量赋值 注意:
1.无论创建多少次对象 静态代码块只会执行一次 2.有作用域限制 3.静态代码块只能直接使用静态资源
public class Person {
static String country = "中国";
int age = 30;
static {
country = "china";
System.out.println("静态代码块 1");
int m = 20;
System.out.println("m = " + m);
}
public Person() {
System.out.println("无参");
}
public static void show() {
System.out.println(country);
}
static {
System.out.println("静态代码块 2");
}
}
public static void main(String[] args) {
//Person.show();
new Person();
System.out.println("-----");
new Person();
}
protected权限修饰符,意思是不同包下的子类可见,但是并不代表不同包下的子对象可见
package com.atguigu.protected1;
public class Person {
protected String name = "Person";
}
package com.atguigu.review;
public class TestStudent {
public static void main(String[] args) {
Student s1 = new Student();
// System.out.println(s1.name);
s1.show();
// s1.name
}
}
package com.atguigu.review;
import com.atguigu.protected1.Person;
public class Student extends Person {
// String name = "梨花";
public void show(){
System.out.println(name);
}
}
package com.atguigu.protected1;
import com.atguigu.review.Student;
public class Test {
public static void main(String[] args) {
Person p = new Person();
System.out.println("p.name = " + p.name);
Student student = new Student();
// System.out.println(student.name);
}
}
测试的话 需要注意包名,person和student是位于两个不同的包下的。在测试类中new一个student对象是看不到父类中的name的,但是在student类中的方法中可以看到父类中的属性name。



