Note that there are some explanatory texts on larger screens.

plurals
  1. POObject assignment using Implementation
    text
    copied!<p>I am trying to get to grips with interfaces and their implementation in Java.</p> <p>I have an interface and 3 classes, 2 of which implement the interface. The implementation of the interface requires 2 methods,</p> <ul> <li><code>toString()</code> <em>[which is using <code>@Overide</code> here for Netbeans satisfaction]</em> and</li> <li><p><code>wheelCount()</code>.</p> <p>public interface IVehicle {<br> @Override public String toString(); public int wheelCount();<br> }</p></li> </ul> <p>We then have the two classes Bike and Car.</p> <pre><code>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; } } </code></pre> <p>Some other class called <code>myClass</code> contains a method to print stuff out... <code>printStuf()</code></p> <pre><code>public void prntStuf(IVehicle myVehicle){ String s = myVehicle.toString(); System.out.println(s); } </code></pre> <p>Assuming an instance of <code>myClass</code> is created, if somewhere in the code we create instances of <code>Bike()</code> and <code>Car()</code>, and we pass these objects into the method <code>prntStuf</code>, what would be the benefit in using either of these assignments. </p> <p><b><i> IVehicle x = new Car()</i></b></p> <pre><code> IVehicle modeoftransport1 = new Car(); IVehicle modeoftransport2 = new Bike(); </code></pre> <p><b><i> As opposed to... Car x = new Car()</i></b></p> <pre><code> Car modeoftransport1 = new Car(); Bike modeoftransport2 = new Bike(); </code></pre> <p>Is there an actual difference or benefit or does it boil down to coding conventions? </p> <p>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.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload