Java Fundamentals (ii)-----polymorphism and constructors

Source: Internet
Author: User

A: Preface

Recently, because of the interview Sina Company, the interviewer asked me questions I do not know, feel good food, so recently decided to put the Java Foundation again, really feel good food. A little bit every day, the guy said, "Java programming thought" at least three times, I have not read it again. Now write your own knowledge of the latest guidance every time. Efforts!!! Just said this on a group, others gave me a word "you have to remind yourself that all the technology others can learn, you can learn sooner or later, no big deal." Remember

II: Content

(1): Questions about the construction method

Each time we write a class, will say in the class add a parameterless construction method, I often think, this parameterless constructor what is the use of, I have been very confused, but now I may understand a bit, because that time to see the source of the next ArrayList I only understand the point, Let's take a look at the ArrayList code.

  

 /*** Constructs an empty list with the specified initial capacity. *     * @paraminitialcapacity The initial capacity of the list *@exceptionIllegalArgumentException If the specified initial capacity * is negative*/     PublicArrayList (intinitialcapacity) {    Super(); if(Initialcapacity < 0)            Throw NewIllegalArgumentException ("Illegal capacity:" +initialcapacity);  This. Elementdata =NewObject[initialcapacity]; }    /*** Constructs an empty list with an initial capacity of ten. */     PublicArrayList () { This(10); }

I wrote a test myself, and here's the following:

1  Packagethinker;2  Public classConstrutsDemo01 {3      PublicString A;4      Public voidfind () {5SYSTEM.OUT.PRINTLN ("My Test Side");6     } 7     8      PublicConstrutsDemo01 () {9          This("5");Ten     } One      A      PublicConstrutsDemo01 (String a) { -          This. a=A; -     } the      -      Public Static voidMain (String args[]) { -ConstrutsDemo01 c=NewConstrutsDemo01 (); -ConstrutsDemo01 c2=NewConstrutsDemo01 ("1"); +SYSTEM.OUT.PRINTLN ("No parameter construction method" +C.A); -System.out.println ("constructor method with parameters" +c2.a); +     } A}

The answer here is that through the constructor, we can either pass arguments or not pass arguments while instantiating. The benefits are obvious. Do not know if this is the benefit of the constructor function!

(ii): deficiencies in polymorphic mechanisms

B: For private methods that cannot be overwritten, the following code

1 Packagethinker;2 3 Public classAnimal {4Private voidFun () {5 System.out.println ("I am a general name for animals"); 6     } 7 Public Static voidMain (string[] args) {8 Animal a=NewDog ();9 A.fun ();//and the result is, "I'm an animal."10     }11 }12 13 14 Packagethinker;15 16 Public classDogextendsAnimal {17 Public voidFun () {System.out.println ("Animals: Dogs"));19     }20 21}

So we came to the conclusion that "there is no way we can override the private approach."

B: A polymorphic domain-domain static method

In fact, I also, just understand the polymorphism of the time I also think, such as the subclass and the parent class have the same variable then if you call this variable, whether it is the same as the method, the call is the sub-class of the variable value. Obviously and I was wrong, only the normal method call can be polymorphic. If you access a domain directly, the access domain will be parsed at the compile time as follows:

 Package thinker;  Public class Animal {    public String name= "Animal";       Public void Fun (String name) {        System.out.println ("I am the animal's name" + ")    }    }
 Packagethinker; Public classDogextendsAnimal { PublicString name= "Cat";  Public voidFun (String name) {System.out.println ("Animals:" +name); }         PublicString GetName () {return Super. Name; }         Public Static voidMain (string[] args) {Animal a=NewDog (); Dog D=NewDog (); System.out.println (a.name);//Print result "Animal" System.out.println ("Name of the parent class:" +d.getname () + "--Subclass:" +d.name);//Print result "Name of the parent class: animal--sub-category: Cat"}}

This is written in the Java programming idea: "When a dog object is transformed into a animal reference, any domain access operations will be parsed by the compiler and therefore not polymorphic"

Talking about static methods: If a method is static, its behavior is not polymorphic:

 Package thinker;  Public class Animal {    public String name= "Animal";       Public Static void Fun (String name) {        System.out.println ("I am the animal's name:" + ")    ;    }  Public void Fprint () {        System.out.println ("parent class: Non-static Class");    }    }
 Packagethinker; Public classDogextendsAnimal { PublicString name= "Cat";  Public Static voidFun (String name) {System.out.println ("Animals:" +name); }     Public voidFprint () {System.out.println ("Subclass: Non-static Class"); }     Public Static voidMain (string[] args) {Animal a=NewDog (); A.fun ("Mouse");//Result "I am the animal's name Mouse" A.fprint ();//Result "subclass: Non-Static Class"}}

It can be seen that our fun () is static, the result of the call printing is also the parent class method, and the Fprint () method is non-static, the call printing result is a subclass method. You can get:

If a method is static, its behavior is not polymorphic

Three: About instantiation order

 PackageOrg.duotai; Public classComputer {Private intI=1;  Public voidfind () {System.out.println ("Computer Find ()"); }     Publiccomputer () {System.out.println ("Computer find () be"); System.out.println ("Construction Method" +i); Find ();//here the call is actually a subclass of the method, but at this time the subclass of data (that is, I) is not instantiated, so in the printed data bits 0SYSTEM.OUT.PRINTLN ("Computer find () af")); }        } PackageOrg.duotai; Public classCpuextendscomputer{Private intI=5;  PublicCPU (inti) {         This. i=i; System.out.println ("Construction Method Cpu.i=" +i); }         Public voidfind () {System.out.println ("Method cpu.i=" +i);//The value is 0 because it is not instantiated at this time    }} PackageOrg.duotai; Public classDTDemo01 { Public Static voidMain (String args[]) {NewCPU (2);//called    }}

The results we print here are:

Computer Find () be constructor Method 1 method cpu.i=0Computer Find () AF construction method cpu.i=2

You can see "method cpu.i=0", so we get that when the parent class is instantiated, the method is called, because the data in the subclass is not instantiated, resulting in this situation.

Instantiation Order: Its own breakpoint is run down, found in the parent class construction or first to initialize the defined variables, and then to execute the contents of the construction method.

*******************************************

Name: Mouse

Famous saying: The opportunity is reserved for the person who prepares, go!

******************************************

Java Fundamentals (ii)-----polymorphism and constructors

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.