Java基础学习:面向对象10(super)
Java基础学习:面向对象10
-
Super():代表父类
-
注意点:
-
super调用父类的构造方法,必须放在构造方法的第一行;
-
super必须出现在子类的方法或者构造方法中;
-
super和this不能同时调用构造方法;
-
-
-
this( ):代表当前类
-
-
代表的对象不同:this代表的是本身调用者;super代表的是父类的引用;
-
this:没有继承也可以使用;super只在继承条件下才可以使用;
-
调用构造方法不同:
-
this调用的是本类的构造方法;super调用的是父类的构造方法;
-
-
-
-
笔记:
-
构造方法:
-
只要写了有参构造,必须显示定义无参构造;
-
如果父类的无参构造没有,那么子类的无参构造无法创建;编译报错!
-
-
-
代码:父类
//父类
public class Person {
public Person() {
System.out.println("无参Person");
}
protected String name="person";
//private,私有的东西无法被继承
public void print(){
System.out.println("printPerson");
}
}
-
代码1:子类
//子类
public class Student extends Person{
public Student() {
//隐藏代码:默认调用了父类的无参构造方法
super();//调用父类的构造器,必须放在子类构造器的第一行
System.out.println("无参student");
}
private String name="Student";
public void test(String name ){
System.out.println(name);
System.out.println(this.name);//当前类
System.out.println(super.name);//父类
}
public void print(){
System.out.println("printStudent");
}
public void test1(){
print();
this.print();
super.print();
}
}
-
代码:main
public class Application {
public static void main(String[] args) {
Student student=new Student();
/*student.test("haha");
student.test1();*/
}
}