简体   繁体   中英

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 extends A{
    int b;
    public int getB(){
        return b;
    } 
    
    public void setB(int b){
        this.b=b;
    }
}

// this is the main 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).

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.

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. By casting the object to its true type you can use all of its methods.

Introduce another variable:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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