简体   繁体   中英

Create new object by parent class

I have an example.

class Candidate is superclass and ExperienceCandidate is subclass.

i have 2 type to create object is:

ExperienceCandidate temp = new ExperienceCandidate();

Candidate temp = new ExperienceCandidate();

Help me distinguish the differences between these two constructs and which one is used in which case

Generally whenever you are creating an object , it is just to create an instance of the class so that you can use it somewhere. In the case of Superclasses and Subclasses , whenever you initiaze a subclass of a class , it already contains all the objects/methods of the superclass. In your case , there are two logical discrepancies :

  • The Candidate temp = new ExperienceCandidate(); is not the correct way to call an object , the correct way to call the object of the superclass is Candidate temp = new Candidate();
  • There is almost no use creating the object of candidate class to use in your superclass as you can just use the keyword super() to call the constuctor of the superclass and anyway all the function of the superclass are available for you to use in the subclass (since you extended to it)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM