Example 1: Parent class: public class Person {public String name;
public int age;
Public person (String Name,int age) {this.name=name;
This.age=age; Public person ()//* If you do not write this constructor, see what effect it has on the class student.
*/{} public void GetInfo () {System.out.println (name);
System.out.println (age);
The subclass: public class Student extends person{String School;
Public Student (String name,int age,string school) {super (name,age);
This.school=school; The public Student () {} is public void study () {System.out.println () ("very good learning.")
");
public static void Main (string[] args) {person p=new person ();
P.name= "Person";
p.age=45;
P.getinfo ();
Student s=new Student ();
S.name= "Student";
s.age=26;
S.getinfo ();
S.study ();
Example 2: In subclasses, you can transform the methods inherited from the parent class----overrides (also called overrides).
The overriding method must have the same method name, parameter list, and return value type as the overridden method.
For example, Example 1, the student program, which inherits the person class's GetInfo method, this inherited method can only print out the student's name and age, can't print out the students ' proprietary information, such as the name of the school, when I
You should rewrite a GetInfo method in the class student, which is the override of the method.
Parent class: Package javatest; public class Person {PUBlic String name;
public int age;
Public person (String Name,int age) {this.name=name;
This.age=age;
//If you do not write this constructor, see what effect it has on the class student.
Public person () {} is public void GetInfo () {System.out.println (name);
System.out.println (age); The subclass inherits the parent class: public class Student extends person{String School;
The parent class is not, and the subclass-specific public Student (String name,int age,string school) {super (name,age);
This.school=school; The public Student () {} is public void study () {System.out.println () ("very good learning.")
");
public void GetInfo () {super.getinfo ();
System.out.println (school);
public static void Main (string[] args) {person p=new person ();
P.name= "Person";
p.age=45;
P.getinfo ();
Student s=new Student ();
S.name= "Student";
s.age=26;
S.school= "Tsinghua University";
S.getinfo ();
S.study ();
}
}