(1)构造方法
对象都有构造方法,如果没有,则添加一个default方法
抽象类有构造方法
(2)调用本类和父类
this 本类其他
super父类
父类所有构造方法都得到调用
例:
class A
{
A(int a){}
}
class B extends A
{
B(String s){} //不能通过编译
}
1.class A
{
A(){}
A(int a){}
}
2.class A
{
}
3.class B extends A
{
super(3);
B(String s){}
}
(3)创建对象时初始化
p = new Person(){{age = 18; name = ' '}}
(4)构造方法执行过程
先父类构造,再本类赋值,最后执行构造方法中的语句
public class MyDate {
public static void main(String[] args){
Person p = new Student("B", 18, "Q");
}
}
class Person
{
String name="A"; //step 2
int age=-1;
Person(String name, int age)
{
super(); //step 1
//step 3
System.out.println( "this.name="+this.name+",this.age="+this.age );
this.name=name; this.age=age;
System.out.println( "Person() this.name="+this.name+",this.age="+this.age );
}
}
class Student extends Person
{
String school="PKU"; //step2
Student( String name, int age, String school )
{
super( name, age ); //step 1
//step 3
System.out.println( "this.name="+this.name+",this.age="+this.age+",this.school="+this.school );
this.school = school;
System.out.println( "Student() this.name="+this.name+",this.age="+this.age+",this.school="+this.school );
}
}
结果:
this.name=A,this.age=-1
Person() this.name=B,this.age=18
this.name=B,this.age=18,this.school=PKU
Student() this.name=B,this.age=18,this.school=Q