暑假自学(19)

super:
super.属性 调用的是父类中的方法
super.构造器
可以在子类构造器中显式使用super(形参列表)的方式,调用父类中声明的指定构造器
super(形参列表)的使用,必须声明在子类构造器的首行
在类的构造器中,针对于this(形参列表)或super(形参列表)只能二选一,不能同时出现
在构造器首行没有显式声明,默认调用父类空参的构造器
子类实例化
子类实例化时会把父类中声明的属性加载到堆中
在调用子类的过程中,我们会一步一步调用父类的构造器直到调用object中的空参构造器为止。
虽然调用了父类的构造器,但只进行new了一个对象。
多态性
例子:public class Person{}
public class Man extends Person{}
Person p1 = new Person();
Person p2 = new Man();//多态
当用子类的构造器定义对象时,调用同名方法使用的是子类重写父类的方法
注意:p2是Person类的,所以只能调用Person类中有的方法,但由于是new Man,所以必须是父类中有并且子类中重写过的方法。

多态性实验代码

public class Person {
public void eat() {
System.out.println("吃饭");
}
}

public class Man extends Person{
public void eat() {
System.out.println("男人吃饭");
}
}

public class Woman extends Person{
public void eat(){
System.out.println("女人吃饭");
}
}

public class text {
public static void main(String[] args) {
Person p1 = new Person();
Person p2 = new Man();
Person p3 = new Woman();
p1.eat();
p2.eat();
p3.eat();
}
}

猜你喜欢

转载自www.cnblogs.com/buxiang-Christina/p/13374790.html