How to access an object's parent object in Java?

后端 未结 4 1375
既然无缘
既然无缘 2021-01-29 01:36

Have a look at this example:

class Parent{
    Child child = new Child();
    Random r = new Random();
}

class Child{

    public Child(){
        //access a me         


        
4条回答
  •  别那么骄傲
    2021-01-29 02:05

    First of all your example doesn't demonstrate parent child relationship in java.

    Its only a class using another type reference.
    in this particular case you can only do new Parent().r //depending upon r's visibility.

    or you can pass the Parent reference to Child (by changing Child's constructor).

    class Parent{
        Child child = new Child(this);
        Random r = new Random();
    }
    
    class Child {
        public Child(Parent p){
            //access a method from Random r from here without creating a new Random()
            p.r.nextBoolean();
        }
    }
    

    In actual inheritance you don't need to do anything, the super class's members are inherited by extending classes. (again available in child class based on their visibility)

    class Parent{
        Child child = new Child();
        Random r = new Random();
    }
    
    class Child extends Parent{
    
        public Child(){
            //access a method from Random r from here without creating a new Random()
            super.r.nextBoolean();
            //or even r.nextBoolean will be same in this case
        }
    }
    

    more at : http://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

提交回复
热议问题