How to access an object's parent object in Jav

2020-05-03 16:57发布

Have a look at this example:

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

class Child{

    public Child(){
        //access a method from Random r from here without creating a new Random()
    }
}

How can I access the Random object from within the Child object?

标签: java oop
4条回答
何必那么认真
2楼-- · 2020-05-03 17:04

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

查看更多
我欲成王,谁敢阻挡
3楼-- · 2020-05-03 17:05

It may be the case that if only your Parent class ever creates instances of Child, for its own internal use, then you could use inner classes, like so:

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

    private class Child {
        Child() {
            Parent.this.r; // Parent's instance of Random
        }
    }
}

There are other reasons why you may want to use inner classes. But, I'm hesitant to suggest them, because requiring access to another class's instance variables is generally not a good practise.

查看更多
够拽才男人
4楼-- · 2020-05-03 17:16

Have the Parent class pass its own instance of Random to the Child class.

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

    public Parent()
    {
        child = new Child(r);
    }
}

class Child{    
    public Child(Random r){

    }    
}

Classic Occam's razor.

查看更多
爷、活的狠高调
5楼-- · 2020-05-03 17:23
  • Yes, If it is static method , you can do that (Random.methodName()).

  • If it is an instance method, A big Noooooo. You definitely need Random instance.

查看更多
登录 后发表回答