Super详解
Super详解
package com.oop.demo05;
//Person 人 :父类
//在java中,所有的类都默认直接或者间接继承Object
public class Person {
//public 公共
//protected 受保护
//default
//private 私有,无法被继承
protected String name = "kuangshen";
public void print(){
System.out.println("Person");
}
}
package com.oop.demo05;
//学生 is 人 :派生类,子类
//子类继承了父类,就会拥有父类的全部方法!
//父类没有无参,子类不能写无参
//父类有无参,子类先调用父类的无参
//super();调用父类的构造器,必须要在子类构造器的第一行
public class Student extends Person{
//Ctrl+H
private String name = "qinjiang";
public void print(){
System.out.println("Student");
}
public void test1(){
print();//Student
this.print();//Student
super.print();//Person
}
public void test(String name){
System.out.println(name);//秦疆
System.out.println(this.name);//qinjiang
System.out.println(super.name);//kuangshen
}
}
//对象的创建
package com.oop;
import com.oop.demo05.Person;
import com.oop.demo05.Student;
//一个项目应该只存在一个main方法
public class Application {
public static void main(String[] args) {
Student student = new Student();
//student.test("秦疆");
student.test1();
}
}
三种代码分别是父类,子类,测试类,代码是super的应用
super注意点
1.super调用父类的构造方法,必须在构造方法的第一个
2.super必须只能出现在子类的方法或者构造方法中
3.super和this不能同时调用构造方法
VS this:
代表的对象不同:
this:本身调用者这个对象
super:代表父类对象的应用
前提
this:没有继承也可以使用
super:只能在继承条件才可以使用
构造方法:
this();本类的构造
super();父类的构造

浙公网安备 33010602011771号