简体   繁体   English

如何在不转换 object 的情况下处理多态性?

[英]How to handle polymorphism without casting object?

 class A{
    int a;
    
    public int getA(){
        return a;
    } 
    
    public void setA(int a){
        this.a=a;
    }
}

// Class B extending A class and add one additional variable // Class B 扩展 A class 并添加一个额外的变量

 class B extends A{
    int b;
    public int getB(){
        return b;
    } 
    
    public void setB(int b){
        this.b=b;
    }
}

// this is the main class // 这是主要的 class

class HelloWorld {
    public static void main(String[] args) {
        
        A aa;
          if(runtime conditon)   {         
                aa= new B();
                  aa.setA(3);
                  ((B)aa).setB(4); 
            }
          else{
          aa= new A();
                  aa.setA(3);
          }
}
}
         


        

How to design to solve the above problem without using casting?如何在不使用铸造的情况下设计解决上述问题? sorry for asking the low-level question (I am new to java).很抱歉提出低级问题(我是java新手)。

Since class B extends class A you can use a variable of type A to point to a variable of type B. But if you want to use only one variable of type A (in your case aa ) you cannot use a method of class B without casting the object.由于 class B 扩展了 class A 您可以使用 A 类型的变量指向 B 类型的变量。但是如果您只想使用 A 类型的一个变量(在您的情况下为aa ),则不能使用没有 DDC 的 ZA2F2ED4F8EBC2CBB4C21A29 的方法铸造 object。

Because you have to remember that when you use a variable (in your case type A) that points to a derived type use (in your case type B), you can only use the methods that are defined in class A, the rest are obscured.因为您必须记住,当您使用指向派生类型使用的变量(在您的案例类型 A 中)(在您的案例类型 B 中)时,您只能使用 class A 中定义的方法,rest 被遮挡. By casting the object to its true type you can use all of its methods.通过将 object 转换为真实类型,您可以使用它的所有方法。

Introduce another variable:引入另一个变量:

B bb= new B();
bb.setA(3);
bb.setB(4); 
aa = bb;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM