Please note, this is a STATIC archive of website www.tutorialspoint.com from 11 May 2019, cach3.com does not collect or store any user information, there is no "phishing" involved.
Tutorialspoint

Simple Inheritance using Java

abstract class GameObject {
    public abstract void touch(GameObject other);
    // NOTE: This is ugly because these two definitions need to be in the main
    //       class, it could be avoided by some more functionality i think?
    public abstract void touch(Mazub other);
    public abstract void touch(Plant other);
}

class Mazub extends GameObject {
    @Override
    public void touch(GameObject other) {
        other.touch(this);
    }
    
    @Override
    public void touch(Plant plant) {
        System.out.println("Mazub touches Plant");
    }
    
    @Override
    public void touch(Mazub mazub) {
        System.out.println("Mazub touches Mazub");
    }
}

class Plant extends GameObject {
    @Override
    public void touch(GameObject other) {
        other.touch(this);
    }
    
    @Override
    public void touch(Mazub mazub) {
        System.out.println("Plant touches Mazub");
    }
    
    @Override
    public void touch(Plant plant) {
        System.out.println("Plant touches Plant");
    }
}


public class HelloWorld {
     public static void main(String []args) {
        GameObject a = new Mazub();
        GameObject b = new Plant();
        a.touch(b);
        b.touch(a);
     }
}

Advertisements
Loading...

We use cookies to provide and improve our services. By using our site, you consent to our Cookies Policy.