Java 如何将子类对象转换为超类对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30414859/
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-08-11 09:35:11  来源:igfitidea点击:

How to cast subclass object to superclass object

javainheritancecastingsubclasssuperclass

提问by Jason

i have 2 classes, called superclass and subclass, i tried to cast the subclass object to superclass, but its seems does not work when i want to use the subclass object from the superclass. Please help to explain. Thanks. These are the code:-

我有 2 个类,称为超类和子类,我尝试将子类对象强制转换为超类,但是当我想使用超类中的子类对象时,它似乎不起作用。请帮忙解释一下。谢谢。这些是代码:-

public class superclass
{
    public void displaySuper()
    }
        System.out.println("Display Superclass");
    }
}

public class subclass extends superclass
{
    public void displaySub()
    {  
        System.out.println("Display Subclass");
    }
}


public class Testing
{    
   public static void main(String args[])
   {
      subclass sub = new subclass();
      superclass sup = (superclass) sub; 

when i tried to use the displaySub() from the subclass get error

当我尝试使用子类中的 displaySub() 时出现错误

      sup.displaySub(); //the displaySub method cant found
   }
}

采纳答案by JohnStrong

A superclass cannot know subclasses methods.

超类不能知道子类的方法。

Think about it this way:

这样想:

  • You have a superclass Pet

  • You have two subclasses of Pet, namely: Cat, Dog

  • Both subclasses would share equal traits, such as speak
  • The Petsuperclass is aware of these, as all Pets can speak (even if it doesn't know the exact mechanics of this operation)
  • A Doghowever can do things that a cat cannot, i.e. eatHomework
  • If we were to cast a Dogto a Pet, the observers of the application would not be aware that the Petis in fact a Dog(even if we know this as the implementers)
  • Considering this, it would not make sense to call eatHomeworkof a Pet
  • 你有一个超类 Pet

  • 你有两个子类Pet,即:CatDog

  • 两个子类将共享相同的特征,例如 speak
  • Pet超意识到这些,因为所有PetS能说话(即使它不知道此操作的确切机制)
  • ADog然而可以做猫不能做的事情,即eatHomework
  • 如果我们将 a 强制转换Dog为 a Pet,应用程序的观察者将不会意识到Pet实际上是 a Dog(即使我们作为实现者知道这一点)
  • 考虑到这一点,调用eatHomework一个Pet

You could solve your problem by telling the program that you know supis of type subclass

你可以通过告诉程序你知道sup的类型来解决你的问题subclass

public class Testing
{    
   public static void main(String args[])
   {
      subclass sub = new subclass();
      superclass sup = (superclass) sub; 
      subclass theSub = (subclass) sup;
      theSub.displaySub();
   }
}

You could solve the problem altogether by doing something like this:

您可以通过执行以下操作来完全解决问题:

public class superclass
{
    public void display()
    }
        System.out.println("Display Superclass");
    }
}

public class subclass extends superclass
{
    public void display()
    {  
        System.out.println("Display Subclass");
    }
}

public class Testing
{    
   public static void main(String args[])
   {
      subclass sub = new subclass();
      superclass sup = (superclass) sub; 
      sup.display();
   }
}

check out this tutorial on more info: overrides

查看本教程了解更多信息:覆盖

回答by HyperNeutrino

Take a look at java inheritance: https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

看看java继承:https: //docs.oracle.com/javase/tutorial/java/IandI/subclasses.html

A subclass can use superclass methods, but a superclass cannot use subclass methods. If you want to call a superclass to use a subclass method, you must first cast the superclass instance to the subclass. (subclass) sup

子类可以使用超类方法,但超类不能使用子类方法。如果要调用超类以使用子类方法,必须先将超类实例强制转换为子类。(subclass) sup

回答by nxhoaf

Even though both super and sub object point to the same object in memory, your super object knows nothing about the existence of sub.subMethod(). Hence, you got the above error. The following figure illustrates what happened:

即使 super 和 sub 对象都指向内存中的同一个对象,你的 super 对象对 sub.subMethod() 的存在一无所知。因此,您收到了上述错误。下图说明了发生的事情:

enter image description here

在此处输入图片说明

回答by Makoto

This isn't going to work, because you're performing a narrowing reference conversion. From the JLS:

这是行不通的,因为您正在执行缩小引用转换。来自 JLS:

From any reference type S to any reference type T, provided that S is a proper supertype of T (§4.10)

从任何引用类型 S 到任何引用类型 T,前提是 S 是 T 的适当超类型(第 4.10 节)

In your scenario, subclassis a proper subtype of superclass. This means it is permissible to declare an instance of a subclassas a superclass:

在您的场景中,subclasssuperclass. 这意味着允许将 a 的实例声明subclass为 a superclass

superclass sc = new subclass();

as you've previously discovered.

正如您之前发现的那样。

However, class membersare only ever transferred via inheritance; that is, the superclass may pass along fields and methods to its subclasses, but the subclass cannot do the same for its superclass.

然而,类成员只能通过继承转移;也就是说,超类可以将字段和方法传递给它的子类,但子类不能为它的超类做同样的事情。

From the JLS:

来自 JLS:

The members of a class type are all of the following:

  • Members inherited from its direct superclass (§8.1.4), except in class Object, which has no direct superclass

  • Members inherited from any direct superinterfaces (§8.1.5)

  • Members declared in the body of the class (§8.1.6)

类类型的成员如下:

  • 从其直接超类(第 8.1.4 节)继承的成员,除了没有直接超类的 Object 类

  • 从任何直接超接口继承的成员(第 8.1.5 节)

  • 在类的主体中声明的成员(第 8.1.6 节)

To tie all of these rather large words together:

将所有这些相当大的词联系在一起:

  • You're travelling upthe inheritance chain from child to parent
  • A parent may pass along methods and fields to its child, but a child cannotpass methods and fields to its parent
  • If you refer to an instance of a subclass by its superclass (as in superclass sc = new subclass();), you cannot access any of the subclass' member fields or methods.
  • 你旅行继承链从孩子父母
  • 父级可以将方法和字段传递给其子级,但子级不能将方法和字段传递给其父级
  • 如果您通过其超类(如superclass sc = new subclass();)引用子类的实例,则不能访问任何子类的成员字段或方法。

As a general programming practice, the only time that you would use a broader class declaration is when you only need that object to do certain operations based on the traits of the parent class or interface, and not anything specific to sub-instances of the class or interface. In this case, you should avoidusing the parent and use the child class instead, as you rely on very specific behavior that is only present in the child class.

作为一般的编程实践,唯一一次使用更广泛的类声明是当您只需要该对象根据父类或接口的特征执行某些操作时,而不是特定于类的子实例的任何操作或界面。在这种情况下,您应该避免使用父类而使用子类,因为您依赖于仅存在于子类中的非常具体的行为。