JAVA study NOTE 2: class inheritance and Polymorphism
I. Inheritance of Classes
① Concept of class inheritance
Java class inheritance can be expressed by the following statements:
ClassParent class// Define the parent class
{}
Class subclass extendsParent class// Use the extends keyword to implement class inheritance
{}
Example:
Package projiect; class Study {String name;} class Hard extends Study {String result;} public class test1 {public static void main (String [] args) {// TODO Auto-generated method stubHard s = new Hard (); s. name = "I"; s. result = "love learning"; System. out. println (s. name + s. result );}}
Result: I love learning.
Of course, there are also multi-level inheritance (parent class A) -- (parent class B) -- (parent class C) -- subclasses, which can be written as follows:
ClassA
{}
Class B ExtendsA
{}
Class C ExtendsB
{}
② Use of super keywords
Example:
Package projiect; class Person {String name; int age; public String talk () {return "I am:" + this. name + ", this year:" + this. age + "years old" ;}} class Student extends Person {String school; public Student (String name, int age, String school) {super. name = name; super. age = age; System. out. print (super. talk (); this. school = school ;}} public class test1 {public static void main (String [] args) {// TODO Auto-generated method stubStudent s = new Student ("James", 23, "UCAS"); System. out. println (", school:" + s. school );}}
Result: I am Xiao Ming, 23 years old, and the school is UCAS.
If you want to restrict subclass to inherit the parent class, you can use private to apply for private variables in the parent class.
Ii. Type Polymorphism
Use an example to introduce Polymorphism
Package projiect; class Person {public void talk1 () {System. out. print ("I am James");} public void talk2 () {System. out. print (", the teacher asked me to get out! ") ;}} Class Student extends Person {public void talk3 () {System. out. print ("I am James");} public void talk2 () {System. out. print (", let the teacher get out! ") ;}} Public class test1 {public static void main (String [] args) {// TODO Auto-generated method stubPerson p = new Person (); // give priority to the function p in the parent class Person. talk1 (); p. talk2 ();}}
The result is: I am James, and the teacher asked me to get out!
If you change Person p = new Person (); To Person p = new Student (); // This is the first function in the Student subclass.
The result is: I am James, and I asked the teacher to get out!