override of Method (Overwrite/override)
classPerson {PrivateString name; Private intAge ; Public voidSetName (String name) { This. name=name;} Public voidSetage (intAge) { This. age=Age ;} PublicString GetName () {returnname;} Public intGetage () {returnAge ;} PublicString GetInfo () {return"Name:" + name + "\ n" + "Age:" +Age ; }}classStudentextendsPerson {PrivateString School; PublicString Getschool () {returnSchool;} Public voidSetschool (String school) { This. School =School;} PublicString GetInfo () {return"Name:" + getName () + "\nage:" +getage ()+ "\nschool:" +School; }} Public classTestoverwrite { Public Static voidMain (String arg[]) {Student Student=NewStudent (); Person Person=NewPerson (); Person.setname ("None"); Person.setage (1000); Student.setname ("John"); Student.setage (18); Student.setschool ("SCH"); System.out.println (Person.getinfo ()); System.out.println (Student.getinfo ()); }}
Testoverwrite.javaSuper keyword
Memory Analysis
how to construct in inheritance
classSuperclass {Private intN; /*Superclass () {System.out.println ("superclass ()"); } */Superclass (intN) {System.out.println ("Superclass (" + n + ")"); This. N =N; }}classSubclassextendsSuperclass {Private intN; Subclass (intN) {//super ();System.out.println ("Subclass (" + n + ")"); This. N =N; } subclass () {Super(300); System.out.println ("Subclass ()"); }} Public classTestsupersub { Public Static voidMain (String arg[]) {//Subclass SC1 = new Subclass ();Subclass SC2 =NewSubclass (400); }}
Testsupersub.java
Exercise 1
Exercise 2
Object class
tostring Method
Public class testtostring{ publicstaticvoid main (string[] args) { new Dog (); System.out.println ("d:=" +D);} } class dog{ public String toString () { return "I ' m a cool dog!" ; }}
Testtostring.javaEquals Method
Public classtestequals{ Public Static voidMain (string[] args) {Cat C1=NewCat (All-in-); Cat C2=NewCat (All-in-); SYSTEM.OUT.PRINTLN (C1==C2); System.out.println (c1.equals (C2)); //rewrite before the same as above }}classcat{intcolor; intheight, weight; PublicCat (intColorintHeightintweight) { This. color =color; This. Height =height; This. Weight =weight; } Public Booleanequals (Object obj) {if(obj = =NULL)return false; Else{ if(objinstanceofCat) {Cat C=(Cat) obj; if(C.color = = This. color && C.height = = This. height && C.weight = = This. Weight) { return true; } } } return false; }}
Testequals.java
J2SE Object-oriented _ method rewriting