(Person类(父类))
package oop.demo04;
//在Java中,所有的类都直接或者间接的继承Object类
public class Person {
public Person() {
System.out.println(“Person无参数构造器执行”);
}
protected String name = "Bronya";
public void print(){
System.out.println("Person");
}
}
(Student类(子类)
package oop.demo04;
//子类继承父类将会有父类的所有方法
public class Student extends Person{
//无参数构造器
public Student() {
//隐藏代码,调用了父类的无参构造
super();//可以不写,但是写了就必须在第一行
//注意:super和this不能同时调用构造方法
//super(“name”);//如果父类是有参构造,子类需要这样写,否则无法调用无参构造
System.out.println(“Student无参数构造器执行”);
}
private String name = "Seele";
public void print(){
System.out.println("Student");
}
public void test1(){
print();//自己类里的名字
this.print();//自己类里的名字
super.print();//继承类的参数
}
public void test(String name){
System.out.println(name);//main传递过来的参数
System.out.println(this.name);//指的是自己类里的名字
System.out.println(super.name);//继承类的参数
}
}
(main方法)
package oop;
import oop.demo04.Student;
public class Application {
public static void main(String[] args) {
Student student = new Student();
student.test(“布洛尼亚”);
student.test1();
}
}