[英]In Java, Does Object of some class created in superclass can be used in subclass
class A
{
class B b;
B b = new b();
}
class B extends A
{
b.function();
}
Here can B use the same object created in A?这里 B 可以使用在 A 中创建的相同对象吗?
Following is your program:以下是你的程序:
class C {
public String cvariable;
public void cfunction(){
System.out.println("string");
}
}
class A {
public C c1;
public void funtiona(){
c1 = new C();
}
}
public class B extends A {
public void functionb(){
c1.cfunction();
}
public static void main(String args[]){
B b = new B();
b.functionb();
}
}
It is correctly throwing null pointer exception.它正确地抛出空指针异常。 It proceed as follows:它进行如下:
functionb()
在 main 方法中调用functionb()
functionb()
you call cfunction()
with c1, but c1 is just an variable of type C(as not initialized yet) which contains null.在functionb()
您使用c1 调用cfunction()
,但c1 只是一个包含空值的C 类型变量(尚未初始化)。 So getting null pointer exception.所以得到空指针异常。See the following program, It will throw java.lang.StackOverflowError
看下面的程序,会抛出java.lang.StackOverflowError
class B{
A a = new A();
public B(){
System.out.println(a.hashCode());
}
}
public class A extends B{
public void show(){
a.hashCode();
}
public static void main(String[] args){
new A().show();
}
}
This is because program goes in the infinite loop, As before creating a child class object it calls the parent class constructor and in parent class for hash code it again calls the child class constructor.这是因为程序进入无限循环,在创建子类对象之前,它调用父类构造函数,在父类中再次调用子类构造函数以获取哈希码。 so an infinite loop所以无限循环
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.