Cases:
First step. Create a Person class
PackageCom.maya.ball; Public classPerson {Private intAge ; PrivateString name; PublicPerson (intage,string name) { This. Age =Age ; This. Name =name; } Public voidspeak () {} Public intGetage () {returnAge ; } Public voidSetage (intAge ) { This. Age =Age ; } PublicString GetName () {returnname; } Public voidsetName (String name) { This. Name =name; }}
Step two. Create the American class to inherit the person class.
PackageCom.maya.basketball;ImportCom.maya.ball.Person; Public classAmericanextendsPerson { Public Doubleheight;----------------------------- new member variable PublicAmerican (intAge,string name,Doubleheight) { Super(age, name); This. Height =height; } Public voidspeak () {System.out.println ("My Age:" + This. Getage () + ", I Call:" +getname () + ", my height:" +height); }}
Step three. Create the Chinese class and agree to inherit the person class
PackageCom.maya.football;ImportCom.maya.ball.Person; Public classChineseextendsperson{PrivateString sex;------------------- new member variable PublicChinese (intAge , String name,string Sex) { Super(age, name); This. Sex =sex; } Public voidspeak () {System.out.println ("My Age:" + getage () + ", I call:" + This. GetName () + ", my Gender:" +sex); } PublicString Getsex () {returnsex; } Public voidsetsex (String sex) { This. Sex =sex; }}
Fourth step. Create a Test1 class that passes the object of person as a parameter in the Show method
Packagecom.maya.test;ImportCom.maya.ball.Person;ImportCom.maya.basketball.American;ImportCom.maya.football.Chinese; Public classTest1 { Public voidShow (person per) {if(perinstanceofAmerican) {American am=(American) per; System.out.println (Am.height); } if(perinstanceofChinese) {Chinese ch=(Chinese) per; System.out.println (Ch.getsex ()); } }}
Fifth step. Create a Main method to make a call
Packagecom.maya.test;ImportCom.maya.ball.Person;ImportCom.maya.basketball.American;ImportCom.maya.football.Chinese; Public classMain1 { Public Static voidMain (string[] args) {person per=NewAmerican (32, "Xiaoming", 175); American American=(American) per; Doubles =American.height; System.out.println (s); Person Ame=NewAmerican (32, "Xiaoming", 180); Ame.speak (); Person Chinese=NewChinese (23, "Xiao Li", "female"); Chinese.speak (); Test1 T=NewTest1 (); T.show (AME); T.show (Chinese); }}
java--references to the parent class refer to the object of the subclass in detail!