Harsha
Harsha

Reputation: 3578

How to use interfaces properly in OOP languages

I had this question for a long time but all the people who answered me didn't give me a proper answer. I think that the interfaces are used in OOP languages for polymorphism and in a situation like below I don't understand how to handle it, [in java]

lets take following interface and two classes,

public interface Vehicle{
    public int noOfWheels();
    public String movingMethod();
}

public class Car implements Vehicle{
    public int noOfWheels(){
            return 4;
    }

    public String movingMethod(){
        return "Drive";
    }
}

public class Flight implements Vehicle{

    public int noOfWheels(){
        return 5;
    }

    public String movingMethod(){
        return "Fly";
    }

    //a behaviour only applicable to a flight
    public int noOfWings(){
        return 5;
    }
}


=======================================
simulation

    Vehicle v1 = new Car();
    System.out.println(v1.noOfWheels());
    System.out.println(v1.movingMethod);

    Vehicle v2 = new Flight();
    System.out.println(v2.noOfWheels());
    System.out.println(v2.movingMethod);
    System.out.println(v2.noOfWings());//this is not working as Vehicle interface doesn't have this method.

So, how can we achive the solution for a this kind of problem. I know that we can create another interface for flight types but I took this example to express my problem.

Upvotes: 2

Views: 197

Answers (3)

Code-Apprentice
Code-Apprentice

Reputation: 83527

In your example, v2 is a Vehicle and the compiler only allows calling methods from this interface. It appears that you understand this. If you want to call methods from the implementing class, you need to perform a cast.

With that said, I'm interested to know if you have encountered this problem in a real program? If so, can you describe what you encountered and why using an interface in this way is an issue?

Upvotes: 0

vishal_aim
vishal_aim

Reputation: 7854

I think in your Vehicle class noOfWings method can also be defined as vehicle can have wings as well (e.g. flight) (Or you can extend Vehicle to create another interface)

Interfaces are used for polymorphism, but in your example there was no polymorphism for wings logically as well. You made it more specialized case for wings by defining it only in Flight class

Upvotes: 1

Paul Bellora
Paul Bellora

Reputation: 55213

I'm not 100% on what your problem is, but it seems like you're asking how you might express additional behavior to a base interface. It's worth knowing that an interface can extend another interface:

public interface Aircraft extends Vehicle {

    public int noOfWings();
}

A class that implements Aircraft will need to implement the methods declared by Vehicle as well as noOfWings.

Upvotes: 2

Related Questions