继承与覆盖
class Person { String name; int age; public Person(String name,int age) { this.name = name; this.age = age; } public Person(){//无参构造方法 this.name = "person name"; this.age = 23; } void pprint() { System.out.println("class:Person; "+"Name: "+this.name+"; age: "+this.age); } } class Student extends Person { String name; int classno; public Student() { this.name = "student name"; this.age = 20; } public Student(String name,int age,int classno) { this.name = name; this.age = age; this.classno = classno; } void sprint() { System.out.println("class:Student; "+"Name: "+this.name+"; age:"+ this.age+";classno: "+this.classno);} } public class VarInherit { public static void main(String[] args) { Student obj1 = new Student(); Student obj2 = new Student("ZhangSan",18,2); obj1.pprint(); obj2.pprint(); obj1.sprint(); obj2.sprint(); } }
class:Person; Name: person name; age: 20 class:Person; Name: person name; age: 18 class:Student; Name: student name; age:20;classno: 0 class:Student; Name: ZhangSan; age:18;classno: 2//结果所示
注*由于是教材上的例题,不在过多解释