JavaNinja
JavaNinja

Reputation: 59

What is the difference between those kind of instantiation?

it's maybe a newbie question but I think it will be helpful for some beginners.

My question is :

public abstract class Person {
    code goes here ....
}

public class Employee extends Person {
    code goes here ....
}

What is the difference between those kind of instantiation ?

Person student = new Employee("Dove","Female",0);

and

Employee student = new Employee("Dove","Female",0);

Upvotes: 0

Views: 102

Answers (3)

Vimal
Vimal

Reputation: 404

Following is difference in both instantiation.

(1) Person student = new Employee("Dove","Female",0);

In this instantiation student is object of Person class so it can't access Employee class specific methods or attributes.

(2) Employee student = new Employee("Dove","Female",0);

Here, in second instantiation student can access Employee class specific methods and attributes as well as Person class because it is extending in Employee class.

This is basic difference in this two statements.

Upvotes: -1

cнŝdk
cнŝdk

Reputation: 32145

It's basically the same thing, but the difference is that:

1- In the first declaration:

Person student = new Employee("Dove","Female",0);

Here student can't access Employee class specific methods or attributes as it's a Person object which contains an Employee instance.

2- But in the second one:

Employee student = new Employee("Dove","Female",0);

Here student can benefit from both Employee and Person attributes and methods.

Please check Polymorphism Oracle Docs for further reading about polymorphism in Java.

Example:

We can see that in this example, where we use Integer and Object classes:

Integer i1= new Integer(0);
//This will run and execute perfectly
System.out.println(i1.intValue());


Object i2= new Integer(0);      
//This will throw an error as `Object` class doesn't have `intValue()` method.
System.out.println(i2.intValue());

This is a live working Demo so you can see that.

Upvotes: 1

Murat Karagöz
Murat Karagöz

Reputation: 37594

They are essentially the same, but the compiler treats Person student as a Person without any type information from the concrete class Employee

Upvotes: 1

Related Questions