Search code examples
javasubclass

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


Solution

  • 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)