继承

public class Person {
protected String name = "父类名字";
}
public class Student extends Person{
private String name = "子类名字";
public void print(String name){
System.out.println(name);
System.out.println(this.name);
System.out.println(super.name);
}
}
public class Application {
//一个项目只有一个main方法
public static void main(String[] args) {
Student student = new Student();
student.print("张三");
}
}
//张三
子类名字
父类名字
public class Person {
protected String name = "父类名字";
public void print(){
System.out.println("父类方法");
}
}
public class Student extends Person{
private String name = "子类名字";
public void print(){
System.out.println("子类方法");
}
public void test(){
print(); //调用自己类的方法
this.print(); //调用自己类的方法
super.print(); //调用父类的方法
}
}
public class Application {
//一个项目只有一个main方法
public static void main(String[] args) {
Student student = new Student();
student.test();
}
}
//子类方法
子类方法
父类方法
public class Person {
protected String name = "父类名字";
public Person() {
System.out.println("父类无参构造器");
}
}
public class Student extends Person{
private String name = "子类名字";
public Student() {
System.out.println("子类无参构造器");
}
}
public class Application {
//一个项目只有一个main方法
public static void main(String[] args) {
Student student = new Student(); //默认调用父类构造方法
}
}
//父类无参构造器
子类无参构造器
Super注意点:
-
super 调用父类的构造方法,必须在构造方法的第一行;
-
super 必须只能出现在子类的方法或者构造方法中;
-
super 和 this 不能同时调用构造方法;
Super VS This 的区别
-
代表的对象不同
- this:本身调用这个对象
- super:代表父类对象的应用
-
提前不同:
- this:没有继承也可以使用
- super:只能在继承条件下使用
-
构造方法: