开发者

Object assignment using Implementation

I am trying to get to grips with interfaces and their implementation in Java.

I have an interface and 3 classes, 2 of which implement the interface. The implementation of the interface requires 2 methods,

  • toString() [which is using @Overide here for Netbeans satisfaction] and
  • wheelCount().

    public interface IVehicle {

    @Override public String toString(); public int wheelCount();

    }

We then have the tw开发者_开发问答o classes Bike and Car.

public class Bike implements IVehicle{
    @Override
    public int wheelCount() {
        return 2;
    }
    @Override
    public String toString(){
        String s = "This is a Bike with " + wheelCount() + " wheels!";
        return s;
    }
}

public class Car implements IVehicle{
    @Override
    public int wheelCount() {
        return 4;
    }
    @Override
    public String toString(){
        String s = "This is a Car with " + wheelCount() + " wheels!";
        return s;
    }
}    

Some other class called myClass contains a method to print stuff out... printStuf()

public void prntStuf(IVehicle myVehicle){
    String s = myVehicle.toString();
    System.out.println(s);
}

Assuming an instance of myClass is created, if somewhere in the code we create instances of Bike() and Car(), and we pass these objects into the method prntStuf, what would be the benefit in using either of these assignments.

IVehicle x = new Car()

    IVehicle modeoftransport1 = new Car();
    IVehicle modeoftransport2 = new Bike();

As opposed to... Car x = new Car()

    Car modeoftransport1 = new Car();
    Bike modeoftransport2 = new Bike();

Is there an actual difference or benefit or does it boil down to coding conventions?

From what I can tell, they both have the same effect, in that they both produce the same outcome. I've looked through previous questions on here and searched the web but can't put my finger on it. Hope this makes sense.


In your example, the type of the variable doesn't matter.

The choice of type is really a choice about what you're going to do with the variable later. When you say:

Car modeoftransport1 = new Car();

You're saying "I am going to be dealing with a new Car in ways where it matters that it's a Car"; for example, if Car had some other, Car-specific, methods, maybe you're going to call those. When you say:

IVehicle modeoftransport1 = new Car();

You're saying "I am going to be dealing with a new Car in ways where it doesn't matter what kind of vehicle it is".

So, yes, coding convention, or coding style, to a large extent.


In the context of this situation they are the same. If you had specific functionality in either of the derived classes, you would need to use the latter if you wanted to call that functionality later in processing when it is in scope (without casting).


It does not matter in those statements, and is considered a BAD practice to use the latter.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜