开发者

How to return parent class in java

开发者 https://www.devze.com 2023-04-11 15:44 出处:网络
I am fairly new to java and in my code I need a child class to be able to make a an obje开发者_运维技巧ct of its parent class I am pretty sure there is a java keyword that does this but when I searche

I am fairly new to java and in my code I need a child class to be able to make a an obje开发者_运维技巧ct of its parent class I am pretty sure there is a java keyword that does this but when I searched Google for it nothing came up.


A nice feature about polymorphism is that every instance of the child type is also an instance of the parent type. All of these "return an object of the parent type";

class Parent
{
  ... stuff
}

class Child extends Parent
{
  Parent newParent1()
  {
    return this;
  }

  Parent newParent2()
  {
    return new Child();
  }

  Parent newParent3()
  {
    return new Parent();
  }


how about using super();


You may be thinking of "super" for the keyword, but that doesn't do what you describe.

A parent class isn't special in Java:

class Parent
{
}

class Child extends Parent
{
    Parent foo()
    {
        return (new Parent());
    }
}


I don't know why you would need to do this. You can just return a new instance of the child and cast it to the parent. This should work. If you have overridden methods or something of that sort and want to be able to access parent methods that is a different issue. Otherwise you can just upcast:

Child child = new Child();
Parent parent = child;

To upcast a Child object, all you need to do is assign the object to a reference variable of type Parent. The parent reference variable cannot access the members that are only available in Child.

Because parent references an object of type Child, you can cast it back to Child. It is called downcasting because you are casting an object to a class down the inheritance hierarchy. Downcasting requires that you write the child type in brackets. For example:

Child child2 = (Child) parent;

If you need to be able to get instances of the parent then as someone has recommended, just have your child return new Parent().

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号