Java 继承的方法给了我空值
我有三个班,分别是儿童班、基础班和学生班。ChildClass扩展了基类。我的ChildClass继承了一个名为dipslayName()的方法,该方法应该打印学生的名字,但它给了我空值。如果我在我的子类中对student对象进行注释,那么它工作正常Java 继承的方法给了我空值,java,inheritance,Java,Inheritance,我有三个班,分别是儿童班、基础班和学生班。ChildClass扩展了基类。我的ChildClass继承了一个名为dipslayName()的方法,该方法应该打印学生的名字,但它给了我空值。如果我在我的子类中对student对象进行注释,那么它工作正常 package com.techmahindra; public class ChildClass extends BaseClass{ Student student = new Student(); public stati
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");
}
}
这是另一类:
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");
}
}
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;
}
}
这是另一类:
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");
}
}
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;
}
}
ChildClass
中的setName()
方法设置在ChildClass
中声明的学生姓名displayName()
显示在基类中声明的学生姓名
因此,在ChildClass中删除学生的声明后,setName
方法将设置正确学生的姓名
在您的子类中,您注释掉了重写的方法displayName
。这将正确显示在您的ChildClass中声明的学生姓名
两个类都包含一个同名变量的事实造成了一些混乱。我给出了不同的引用名称,这就是它的想法。所以在这里我试着叫student1的名字而不是student2。如果我们为引用提供相同的名称,就会发生这种情况;)
package com.techmahindra
公共类ChildClass扩展了基类{
学生2=新学生()
}您有两个不同的student
字段-一个在BaseClass
中,另一个在ChildClass
中。我强烈怀疑您不希望这样。1您已经注释掉了该函数,那么您希望它如何工作?它是一个空函数,那么它在哪里给你空值呢?3该函数的两种实现方式相同。怎么回事?!您已经在BaseClass
以及ChildClass
中定义了成员变量student
。请注意,这是两个独立的变量。删除此行Student=new Student()
来自您的ChildClass
@Biffen,即使我将其注释掉,因为方法displayName()是在ChildClass中继承的,所以它认为我声明的是正确的?如果是的话,那就是这样<代码>公共类ChildClass扩展基类{Student Student=new Student();公共静态void main(字符串[]参数){ChildClass child=new ChildClass();child.displayName();}公共void displayName(){setName();System.out.println(Student.getName());}公共void setName(){Student.setName()(“Mahesh”);}}