-1

Why do we create objects of one class and assign to reference type of different class. I have two classes say Employee and Student, what is the purpose of creating object like

Employee emp = new Student();

How does this work? And in what cases do we create objects like this?

Stultuske
  • 9,296
  • 1
  • 25
  • 37
Susmitha
  • 93
  • 13
  • 1
    Quite a few reasons. Maybe you want to prevent the calling of methods that are declared in Student which are not present in Employee. Maybe you are coding to interfaces, .. – Stultuske Mar 13 '19 at 08:30
  • 2
    Start [here](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html). – Mena Mar 13 '19 at 08:31

1 Answers1

0

Let's say there are two classes Employee and Student. According to your example

Employee emp=new Student()

Employee class should be the parent class and Student class is the child class. Let's say child accesses parent's members. It's just like this;

class Employee{
    String empName = "John";
}

class Student extends Employee{ 
   int age = 20;
}



class Test{
   public static void main(String[] args){

     Student s= new Student();
     System.out.println(s.empName);  //valid since child class can access members of 
                                                                     parent class 

     System.out.println(s.age);  //valid

     Employee emp=new Student();  //your example
     System.out.println(emp.empName); //valid
     System.out.println(emp.age);  //not valid since parent class can't access child members

 }
}
Devil10
  • 1,853
  • 1
  • 18
  • 22