super this
this:调用对象指向自身的指针
super:指向父类对象的指针
问题:控制台打印的内容是?为什么?(提示:通过debug跟踪观察)1、在子类构造方法执行时,如果没有显示调用父类构造方法,则会隐示在第一行调用super(),代表调用父类空构造方法。
2、如果在子类构造方法Student()中,显示调用了父类的构造方法,则系统不会再自动调用任何父类构造方法了。
问题:
1、能调用super()方法吗?
回答:不能。因为super(..)必须写在第一行,即只能有一个生效。
多个父类构造函数的调用
package com.iit.demo;
public class Person {
public Person(){
System.out.println("Person:空构造方法");
}
public Person(String name){
System.out.println("Person:非空构造方法"+name);
}
}
package com.iit.demo;
public class Student extends Person {
public Student(){
//调用super()方法必须写在第一行
super("张三");
System.out.println("Student:空构造方法");
}
}
package com.iit.main;
import com.iit.demo.Student;
public class Start {
public static void main(String[] args) {
Student s1 = new Student();
}
}
在子类如果不写this,就相当于写了this
在子类指定super,就显式调用父类成员
类的属性或方法统称为类的“成员
package com.iit.demo;
public class Person {
public int age = 50;
public void run(String msg){
System.out.println("Person:"+msg);
}
}
package com.iit.demo;
public class Student extends Person {
public int age = 20;
public void run(String msg){
System.out.println("Student:"+msg);
}
public void showAge(){
System.out.println("age="+age);
System.out.println("thsi.age="+this.age);
System.out.println("super.age="+super.age);
}
public void showRun(){
run("直接run");
this.run("this.run");
super.run("super.run");
}
}
import com.iit.demo.Student;
public class Start {
public static void main(String[] args) {
Student s1 = new Student();
//s1.showAge();
System.out.println("-----");
s1.showRun();
}
}

浙公网安备 33010602011771号