简体   繁体   中英

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?

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:

  • In the main method you call functionb()
  • In functionb() you call cfunction() with c1, but c1 is just an variable of type C(as not initialized yet) which contains null. So getting null pointer exception.

See the following program, It will throw 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM