santhosh2759 santhosh2759 - 3 months ago 12
Java Question

Inherited method is giving me the null value

I have three classes named ChildClass, BaseClass and Student. ChildClass extends BaseClass. My ChildClass inherits a method called dipslayName() which should print the name of the student but it is giving me the null value. If I comment the student object in my ChildClass it is working fine.

package com.techmahindra;

public class ChildClass extends BaseClass{
Student student = new Student();

public static void main(String[] args) {
ChildClass child = new ChildClass();
child.displayName();
}

/*public void displayName(){
setName();
System.out.println(student.getName());
}*/
public void setName(){
student.setName("Mahesh");
}
}


This is the other class:

package com.techmahindra;

import com.techmahindra.Student;

public class BaseClass {
Student student = new Student();
public void displayName(){
setName();
System.out.println(student.getName());
}
public void setName(){
student.setName("santhosh");
}
}


This is the other class:

package com.techmahindra;

public class Student {
private int id;
private String name;

public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

Answer

The setName() method within your ChildClass sets the name of the student that is declared within your ChildClass.
The displayName() displays the name of the student as it is declared within the BaseClass.
Thus, removing the declaration of the student within the ChildClass, the setName method will set the name of the correct student.

Within your ChildClass you commented out the overridden method displayName. This would correctly display the name of the student as it is declared within your ChildClass.

The fact that both classes contain a variable with the same name creates some confusion.

Comments