简体   繁体   中英

Is there any way to access a sub-type method without casting using generic

To access sub-class method down-casting is needed, is there is a way to achieve this using generic without type-casting in same manner.

public class Main {
    public static void main(String[] args){

        Animal parrot = new Bird();
        ((Bird)parrot).fly();
    }
}

interface Animal{
    void eat();
}
class Bird implements Animal{
    @Override
    public void eat() {}
    public void fly(){}
}
public class Main {
    public static void main(String[] args){

        Animal parrot = new Bird();
        parrot.move();
    }
}

interface Animal{
    void eat();
    void move();

}
class Bird implements Animal{
    @Override
    public void eat() {}
    public void move(){fly();}
    public void fly(){}
}

It could work with something like this I guess

Interfaces are meant to add methods to implemented classes without defining actual code for this method, meaning that any implemented class will definitely have the same methods but 2 implemented methods with the same name won't necessarily perform the same action.

To explain it with the current thread it would be:

interface Animal {
    void move();
}

class Bird implements Animal{
    public void move(){
        fly();
    }
}

class Dog implements Animal{
    public void move(){
        walk();
    }
}

This way, each class will have its own definition of the move method while in main each method will be called by object.move() .

This way of doing things allows to go from a code like this

for (object tmp:objList){
   if(tmp.class=="Bird")
      tmp.fly();
   }
   else if (tmp.class=="Dog"){
      tmp.walk();
   }
...
}

to

for (object tmp:objList){
    tmp.move();
}

The parrot class should extend the Bird class, then you can call the fly method from a parrot object directly and without need to cast.

public class Parrot extends Bird{

//have some filed or method

}

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