ary
ary

Reputation: 91

implementing UML diagram to java code (uses both aggregation and polymorphism)

I'm working on a java exercise that has me a bit confused. How can I use polymorphism while the methods are in an interface? Some help would be appreciated.

Setters and getters can be omitted.

What I have so far:

Interface:

interface Interface {
    public void start();
    public void stop();
}

First Class:

class Class1 implements Interface {

    private String brand;

    @Override
    public void start() { 
    System.out.println("Hello from start"); }

    @Override
    public void stop() { 
    System.out.println("Hello from stop");}
}

Class 2:

class Class2 implements Interface {

    private String plate;

    @Override
    public void start() { 
   System.out.println("Hello from start");
   }

    @Override
    public void stop() { 
    System.out.println("Hello from stop");}
    }

Aggregation Class:

class Aggregate {

    private String destination;
    private String starting;

    public void trip(interface : Interface) {
        interface = new Aggregate(Interface);
    }
}

Upvotes: 1

Views: 106

Answers (1)

Thilina Samiddhi
Thilina Samiddhi

Reputation: 326

An interface in java, is a collection of abstract methods. When a class implements an interface, it inherits the abstract methods of the interface, so that the class can add a body to those methods specifically for itself. In other words, the class can override those methods mentioned in the interface. I believe you know that overriding and overloading are two types of polymorphism in java. So, in your answer above, you have indeed used polymorphism correctly. Just, add a simple method body relevant to the class, like printing something to the screen (as mentioned in the assignment), in order to add more meaning.

Upvotes: 3

Related Questions