Nawaf Abdu Nawaf Abdu - 2 months ago 6
Java Question

if there are two methods with same name in Parent class and Child Class ..?

if there are two methods with same name in Parent class and Child Class ..?

for example :
parent class is :

public abstract class Employee implements Payments {
private String name;
protected double basicSalary;
public Employee( String name , double basicSalary )
{
this.basicSalary = basicSalary;
this.name = name;
}
public void display()
{
System.out.println( " Name: " + name + " - Basic Salary: " + basicSalary +"SR" );
}


and the Child is :

public class Faculty extends Employee {
private String degree;
private int teachingHours;

public Faculty( String name , double salary , String degree , int teachingHours)
{
super(name , salary );
this.degree=degree;
this.teachingHours = teachingHours;
}
public void display()
{
System.out.println( " Name: " +getName() + " - Degree:" +degree);
}


and i create an object like this ..

Employee [] arrEm = new Employee [4];

arrEm[0]= new Faculty("ahmad" , 1000 , "Phd" , 10 );


so if i write

arrEm[0].display();




this way method display will be used in child
but in case we want to use the method display in Parent Class .. How it can be done ?

Thanks in advance !

Answer

This is because first you do Employee [] arrEm = new Employee [4]; this will make arrEm array for objects then you do this arrEm[0]= new Faculty("ahmad" , 1000 , "Phd" , 10 ); you use the arrEm[0] to refer a child class object so it will use display of the child this is a normal case of polymirphism you can search it on google its useful. If you want to use the parent display use

arrEm[0] = new Employee;

or there is a way to upcast like

child a= new child();

Parent p=(Parent)a;

this a.display() will use the display in the parent class