super注意点:
1.super调用父类的构造方法,必须在子类构造方法的第一个
2.super必须只能出现在子类的方法或者构造方法中
3.super和this不能同时调用构造方法
和this的区别:
代表的对象不同:
this:本身调用者这个对象
super:代表父类对象的引用
前提:
this:没有继承也可以使用
super:只能在继承条件下才可以使用
构造方法:
this();本类的构造
super();父类的构造
=====================================================
构造父类Person
package oop.Demo02;
//在java中,所有的类,都默认直接或间接继承Object
//父类
public class Person {
//public
//protected
//default
//private
//private修饰的属性,子类无法调用
protected String name = "gmt";
//私有的东西无法被继承,属性为private,子类就无法调用
public void print(){
System.out.println("父类的输出");
}
public Person() {
System.out.println("Person的无参构造");
}
}
=====================================================
构造子类Boy
package oop.Demo02;
//继承
//男孩是人 子类
//子类继承父类,就会拥有父类的全部方法
public class Boy extends Person {
//ctrl + h查看继承树关系
public Boy() {
//隐藏代码:调用了父类的无参构造
super();//调用父类的构造器,必须在子类构造器的第一行
System.out.println("Boy的无参构造");
}
private String name = "tmg";
public void test(String name){
System.out.println(name); //111
System.out.println(this.name); ///tmg,调用自己的属性
System.out.println(super.name); ///gmt,子类调用父类的属性
}
public void print(){
System.out.println("子类输出");
}
public void test1(){
print();
this.print();
super.print();
}
}
=====================================================
Main()函数调用
package oop;
import oop.Demo02.Boy;
public class Application {
public static void main(String[] args) {
Boy boy = new Boy();
boy.test("111");
boy.test1();
}
}
=====================================================
结果