How to design a solution that needs dynamism using Inheritance [closed]

I have below code/classes/interfaces:

  1. An Interface:

     public interface Animal<A extends Animal<A>>{
     void fight(A otherAnimal);
     }
    

2.Tiger class which is implementing Animal

    public class Tiger implements Animal{
    @Override
    public void fight(Tiger otherAnimal) {
        System.out.println("Tiger Fights");
    } 
} 

3. I have a Lion class which also implements Animal

  Public class Lion implements Animal{
 @Override
 public void fight(Lion otherAnimal) {
    System.out.println("Lion Fights");
}
  1. I have a test class which is going to call fight:

    public class TestClass{
    public static void main(String[] args){
       Animal tiger = new Tiger();
       Animal lion = new Lion();
       tiger.fight(lion); 
       } 
    }
    

Now when I run the test class the obvious output is “Tiger Fights”.

How should I redesign so that when I call fight on tiger with anything other than tiger should call their respective classes.

So in the example above it should invoke lion’s fight even if the fight is called on object of tiger.

I need output as “lion fights” even if I am invoking an object of tiger. Meaning actually I want developer to have freedom to pass any type of object to to any class. My expectation is based on type of object the respective overridden method has to be called.

I need this dynamism because there can be N number of different animals (cat, dog, wolf etc) which might get added in near future.

Is it possible to design in such a way that My Animal interface will decide which class to call depending of type of object passed?

13

First of all, you’re setting up Animal interface with generics in order to make the Animal instance passed to fight as the same as the one implementing Animal. In other words, Lion can only fight a Lion. A Tiger can only fight a Tiger. From the sounds of it, you want to be able to fight any animal. If you don’t need to use A for any other reason in interface, ditch it. It isn’t helpful.

public interface Animal {
  void fight(Animal otherAnimal);
}

Second, now that you’re receiving an Animal instance, you need to know if it is an instance of the very same class implementing Animal.

To do this, you could simply write:

public class Tiger implements Animal{
    @Override
    public void fight(Animal otherAnimal) {
        if(otherAnimal.getClass().equals(this.getClass()) {
            System.out.println("Two tigers fight");
        } else {
            System.out.println("Tiger fights a " + otherAnimal.getClass().getName());
        }
    } 
} 

This works fine so long as you don’t need to know what type otherAnimal is. In other words, if you start constructing if.. else lists to cover every possibility, you’re doing it wrong. Tiger should know how it fights other animals, and anything that might change the outcome should be something that all Animal instances have.

For instance, if you want to attack “Pokemon” style with each animal having its own health bar, you need not cast it to Lion to get the Lion‘s health points. You need only create a “getHealthPoints” method in Animal.

If you’re using Java 8, you can even make use of defaults in your interface and override only if your subclass needs to behave differently:

public interface Animal {
  default void fight(Animal otherAnimal) {
     if(otherAnimal.getClass().equals(this.getClass()) {
         System.out.println("Two " + this.getClass().getName() + "s fight");
     } else {
         System.out.println(this.getClass().getName() + " fights a " + otherAnimal.getClass().getName());
     }
  }
}

For this particular example, this should be sufficient, though if you’re looking for an example of Visitor pattern, the wikipedia article on Visitor pattern provides a decent explanation. Note that the structure is more hierarchical and serves primarily for performing an operation on each object in it. This would be a bit of an overkill for this particular instance, so I won’t modify the above example.

Hope that helps.

If you are looking for a class for code that calls a winner of 2 animals fighting, then the solution is a third class that does that. Imagine you have to write a compare method that compares objects of 10 very different classes. Obviously you can’t have code doing the comparing spread out all over those 10 classes. It’s much cleaner to write a Comparator class.

If you are just asking how to write code x operation y where you can code operation for each x and y type pair separately then you’re looking for dual dispatch, usually implemented by Visitor pattern.

Edit: you are also misusing generic types. You are adding generic type of A to whole Animal type just for the target type of fight method. You should add generic type to the method only.

The correct declaration of animal would be:

public interface Animal {
    <A extends Animal> void fight(A otherAnimal);
}

1

From what you wrote, it is still a little bit unclear what you are after, but I guess when a “Tiger” fights a “Lion”, you do not want to have printed “Tiger fights” or “Lions fights”, but something like “Tiger fights Lion”. And that is nothing for which you need double dispatch or the visitor pattern.

Just separate the “output part” from the “who fights” part:

public interface Animal {
   String Race();
   int Strength();
}

public class Tiger implements Animal{
  @Override
  public String Race() {
      return "Tiger";
  } 
  @Override
  public int Strength() {
      return 10;
  } 

(yes, the Race part could be more elegantly implemented by using this.getClass().getName(), but this is for demonstration purposes). I have added an additional Strength method to make clearer how this works and how to implement actual logic with it. Place the fight method (the output part) somewhere else, and implement it in terms of “Animals”:

public class Arena {
public void fight(Animal a1, Animal a2) {
    System.out.println(a1.Race() + " fights " + a2.Race());
    if(a1.Strength()>a2.Strength)
    {
         System.out.println(a1.Race() + " wins");
    }
    else if(a1.Strength()<a2.Strength)
    {
         System.out.println(a2.Race() + " wins");
    }
    else
    {
         System.out.println("Tie.");
    }
} 

Now you can easily add more different animals, without touching any of the existing animal classes or touching the fight method.

2

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật