Re: newbie interface question
happytoday wrote:
I am testing interface but really I can not apply what is explained in
oracle tutorials . Could you please explain why I have errors with
this code :
Besides the fact that your example may or may not compile, there are
some sever issues with the way to design and use classes.
For better encapsulation, do not directly access fields of an object
outside of it. You already wrote setters, but you are not using them.
Also Java best practice is to prefix getters with "get" and setters with
"set". If you look again into the Java Tutorial, you will see that the
Bicycle class is actually written that way.
So Bicycle and its usage would be
class Bicycle {
private int speed;
private int cadence;
private int gear;
public int getSpeed() { return speed; }
public void setSpeed(int speed) { this.speed = speed; }
// add other getters and setters in the same way
public void printResults() {
System.out.println("Bike: [" + speed + ", " + cadence +
", " + gear + "]");
}
}
Bicycle bike1 = new Bicycle();
bike1.setSpeed(1);
// set other data
bike1.printResults();
This way, you can later add checks to the setters (i.e. if your bike
only has 10 gears, you can handle setting it you gear 11 in an
"intelligent" way).
Also, there is no need to redeclare fields of a class that you inherit
from. Since speed, cadence and gear are already declared for Bicycle,
you do not need to redeclare them for MountainBicycle:
class MountainBicycle extends Bicycle {
public void printResults() {
System.out.println("MountainBike: [" + speed + ", " + cadence +
", " + gear + "]");
}
}
Bicycle bike2 = new MountainBicycle();
bike2.setSpeed(1);
// set other data
bike2.printResults();
BTW: Another good practice is instead of your printResults() method to
declare a method called toString() that converts the data to a String
and then use System.out.println from the caller:
class Bicycle() {
// ...
public String toString() {
return "Bike: [" + speed + ", " + cadence +
", " + gear + "]";
}
}
Bicycle bike1 = new Bicycle();
System.out.println(bike1.toString());
This allows more flexibility. For example, if you decide to write the
data to stderr instead of stdout, you only need to change the calling
code to
System.err.println(bike1.toString());