Super详解
super注意点
-
super调用父类的构造方法,必须在构造方法的第一个
-
-
super和this不能同时调用构造方法!
Vs this
代表的对象不同:
-
this:本身调用者这个对象
-
super:代表父类对象的引用
前提:
-
this:没有继承也可以使用
-
super:只能在继承条件下才可以使用
构造方法
-
this():本类的构造
-
super():父类的构造!
举例
super()必须在第一行,否则会报错

this()也必须在第一行,否则会报错,因此不能和super()同时调用

this()写第一行,super()会报错

无参构造

写了有参构造,无参构造就没了

父类没有无参构造,子类里面没法调用super()

因此子类无参构造也会报错

因此父类必须加一个无参

如果父类想写有参构造,子类可以调用父类的有参构造,不写的话就默认调用无参构造

代码
//Java-零基础学习/src/oop/demo05/Student
package oop.demo05;
//Student is Person :派生类,子类
//子类继承了父类,就会拥有父类的全部方法!
public class Student extends Person {
public Student() {
//隐藏代码:调用了父类的无参构造
super();//调用父类的构造器,必须要在子类的第一行
System.out.println("Student无参执行了");
}
private String name = "qinjiang";
public void print() {
System.out.println("Student");
}
public void test1() {
print();
this.print();
super.print();
}
public void test(String name) {
System.out.println(name);//秦疆
System.out.println(this.name);//qinjiang
System.out.println(super.name);//kuangshen
}
}
/*
public static void main(String[] args) {
Student student = new Student();
student.test("秦疆");
student.test1();
}
*/
//Java-零基础学习/src/oop/demo05/Teacher
package oop.demo05;
//在Java中,所有的类,都默认直接或者间接继承object
//Person 人:父类
public class Person {
public Person() {
System.out.println("Person无参执行了");
}
protected String name = "kuangshen";
public void print() {
System.out.println("Person");
}
}
//Java-零基础学习/src/oop/Application
package oop;
import oop.demo05.Student;
//一个项目应该只存在一个main方法
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.test("秦疆");
student.test1();
}
}

浙公网安备 33010602011771号