Inheritance and Polymorphism

Source: Internet
Author: User

Inheritance and Polymorphism

1. Run TestInherits. java example, observe the output, pay attention to sum up the call relationship between the constructor of the Parent class and the subclass to modify the code of the Parent constructor, and explicitly call another constructor of GrandParent, note whether this call code is the first one, which has a major impact!

class Grandparent {    public Grandparent() {        System.out.println("GrandParent Created.");    }    public Grandparent(String string) {        System.out.println("GrandParent Created.String:" + string);    }}class Parent extends Grandparent {    public Parent() {        //super("Hello.Grandparent.");        System.out.println("Parent Created");       // super("Hello.Grandparent.");    }}class Child extends Parent {    public Child() {        System.out.println("Child Created");    }}public class TestInherent {    public static void main(String args[]) {        Child c = new Child();    }}

Result:

Summary: calling the base class constructor through super must be the first statement in the subclass constructor. Before running the subclass constructor, you must call the constructor of the parent class. Because inheritance adds new variables and methods on the basis of existing classes to generate a new class, subclass must be inherited on the basis of the parent class, and cannot be reversed.

2. Immutable class instance: Address. java

Source program:

Public final class Address {private final String detail; private final String postCode; // initialize two instance attributes in the constructor: public Address () {this. detail = ""; this. postCode = "";} public Address (String detail, String postCode) {this. detail = detail; this. postCode = postCode;} // only provides the getter method public String getDetail () {return this. detail;} public String getPostCode () {return this. postCode;} // rewrite the equals party To determine whether two objects are equal. Public boolean equals (Object obj) {if (obj instanceof Address) {Address ad = (Address) obj; if (this. getDetail (). equals (ad. getDetail () & this. getPostCode (). equals (ad. getPostCode () {return true;} return false;} public int hashCode () {return detail. hashCode () + postCode. hashCode ();}}

Result: No result is returned.

Summary: what is the use of an unchangeable "class? (1) It can be conveniently and securely used in multi-threaded environments. (2) access to them can be done without locking, thus providing high performance.

Iii. See the configurationjdksource. java example.

In this example, A Class A is defined and has no members:

Class {}

Source program:

public class ExplorationJDKSource {    /**     * @param args     */    public static void main(String[] args) {        System.out.println(new A());    }}class A{}

Result:

Conclusion: In the previous example, the main method actually calls public void println (Object x), which internally calls the valueOf method of the String class. The valueOf method calls the Object. toString method internally:

Public String toString (){

Return getClass (). getName () + "@" +

Integer. toHexString (hashCode ());

}

The hashCode method is a local method, which is implemented by the JVM designer:

Public native int hashCode ();

4. Magic plus sign

Source program:

public class Fruit{            public String toString()    {        return "Fruit toString.";    }    public static void main(String args[])    {        Fruit f=new Fruit();        System.out.println("f="+f);    //    System.out.println("f="+f.toString());    }}

Result:

To sum up, a string is added to an Object and the result is a string because the Fruit class overwrites the toString method of the Object class. In the "+" operation, when an object is connected to a String object, its toString () method is called implicitly. By default, this method returns "Class Name @ + hashCode ". To return meaningful information, subclass can override the toString () method. Method override requires that the subclass and the parent class have the same method; otherwise, the method is overloaded ).

5. Write your own code to test the following features (start-up): In the subclass, you can use the super keyword to call the override method in the parent class.

Source program:

Class Grandparent {public Grandparent () {// method overload System. out. println ("Grandparent Created. ");} public Grandparent (String string) {System. out. println ("GrandParent Created. string: "+ string) ;}} class Parent extends Grandparent {public Parent () {super (" Hello. grandparent "); System. out. println ("Parent Created"); // super ("Hello. grandparent ") ;}} class Child extends Parent {public Child () {System. out. println ("Child Created") ;}} public class TestInherent {public static void main (String args []) {Child c = new Child (); // constructor }}

Result:

Summary: In the Parent subclass, if you want to call the method Grandparent () that is overwritten in the Parent Grandparent class, the result is as follows after the super keyword is used.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.