Java - 从子对象获取父对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26900655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 10:50:16  来源:igfitidea点击:

Java - get parent object from child object

javaoopinheritance

提问by Fahad Mullaji

I am trying to get base object from parent object but i am not able to. Do we have anything like this?`

我正在尝试从父对象获取基础对象,但我无法做到。我们有这样的事情吗?`

public class A
{
}

public class B extends A
{
    A obj = this.getParentObject();     
}

Thanks Fahad Mullaji

感谢法哈德·穆拉吉

回答by Olavi Mustanoja

You should read how the superkeyword and inheritanceworks in Java.

您应该阅读super关键字和继承在 Java 中是如何工作的。

Getting the superclass, or the class your class extends, is not really necessary in the general case. See the below illustration:

在一般情况下,获取superclass或您的类扩展的类并不是真正必要的。请参阅下图:

public class A {

    protected int value;

    public A() {
        this.value = 2;
    }

}

public class B extends A {

    public B() {
        System.out.println(value); // prints 2
    }

}

To refer to the superclass, use the superkeyword. See example below:

要引用超类,请使用super关键字。请参阅下面的示例:

public class A {

    public void doStuff() {
        System.out.println("parent");
    }

}

public class B extends A {

    public B() {
        doStuff(); // prints "child"
        super.doStuff(); // prints "parent"
    }

    @Override
    public void doStuff() {
        System.out.println("child");
    }

}

I hope this answers your question.

我希望这回答了你的问题。



The hacky and generally unneccessary stuff

hacky 和一般不必要的东西

You CAN, of course, get the parent object. For this I recommend making a protected (or public) method for the class A that returns itself. See code example below:

当然,您可以获取父对象。为此,我建议为返回自身的类 A 创建一个受保护的(或公共的)方法。请参阅下面的代码示例:

public class A {

    protected A getMe() {
        return this;
    }

}

public class B extends A {

    public B() {
        A superInstance = getMe();
    }

}

This is untested code, but I can't see why it wouldn't work.

这是未经测试的代码,但我不明白为什么它不起作用。

回答by Daniel Liberman

There's no such thing. You instantiate an object from class B, which extends A. It's just one object, does not "contain" A inside it. Let's say A has also other properties:

没有这样的事情。你从类 B 实例化一个对象,它扩展了 A。它只是一个对象,里面不“包含”A。假设 A 还具有其他属性:

public class A
{
  public int a;
}

public class B extends A
{
  public int b;
}

Objects from class B will have both attributes a and b.

来自 B 类的对象将同时具有属性 a 和 b。

With "super" keyword you can access the methods from the base class. But you can't "get the object" from the base class.

使用“super”关键字,您可以访问基类中的方法。但是你不能从基类“获取对象”。