Home > database >  What is the difference in creating an object in Java using these two approaches?
What is the difference in creating an object in Java using these two approaches?

Time:01-17

In this instance the Doctor class inherits properties from an Employee class. What is the main difference if I create this object like so:

Employee employee1 = new Doctor();

vs.

Doctor doctor1 = new Doctor();

I’m unsure what to expect or look for when comparing differences.

CodePudding user response:

Assuming you're asking about Java, the difference is:

  • employee1 will only give you access to the fields and methods of the Employee class/interface
  • doctor1 will give you access to all the fields and methods of the Doctor class

CodePudding user response:

The main difference is that when you create an object like "Employee employee1 = new Doctor();", you are assigning an object of type Doctor to a variable of type Employee. This is known as upcasting, and it allows you to access all of the properties from the Employee class. However, you will not be able to access any of the properties from the Doctor class when using this method.

When you create an object like "Doctor doctor1 = new Doctor();", you are creating an object of type Doctor and assigning it to a variable of type Doctor. This is known as downcasting and it allows you to access all of the properties from both the Employee class and the Doctor class.

  • Related