this与super的不同
代表的不同
this:当前类的
super:父类的
前提
this:没有继承也可以用
super:只能在继承条件下才可以使用
构造方法
package com.jiemyx.oop.demo06;
public class Person {
//Person类的构造器(构造方法)
public Person(){
System.out.println("Person类的构造器(构造方法)");
}
protected String name = "人类";
//如果是private私有的,在Student类中就无法使用super.print()
public void print(){
System.out.println("Person类中的print方法");
}
}
package com.jiemyx.oop.demo06;
public class Student extends Person{
//Student类的构造器(构造方法)
public Student(){
//隐藏代码:调用父类的无参数构造方法
//super();
//显示出来,调用父类的构造方法,必须在子类构造方法的第一行
super();
System.out.println("Student类的构造器(构造方法)");
}
private String name = "xiaoming";
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("Student类中的print方法");
}
public void test1(){
print();
this.print();
super.print();
}
}
package com.jiemyx.oop.demo06;
public class Application {
public static void main(String[] args) {
//创建对象,并且调用构造器
Student student = new Student();
System.out.println("=========");
student.test("小明");
System.out.println();
student.test1();
}
}
运行结果:
Person类的构造器(构造方法)
Student类的构造器(构造方法)
=========
小明
xiaoming
人类
Student类中的print方法
Student类中的print方法
Person类中的print方法
原文:https://www.cnblogs.com/Jiemyx/p/14664602.html