Reputation: 5298
I'm having some more confusion on interfaces/inheritance. Here's the example situation. A car class has a private member, gear. A sports car and a van extend car. They are both cars. Only a sports car, though, should be able to set the gear. A van can not change the gear (bear with me).
So then there is an interface, IGearChangable. Sports car implements this interface. So then sports Car class has a method called setGear. My question is, how do I access gear? If I make anything in Car protected, the ability to alter gear is still available to the Van class, even though the van should NOT be able to change the gear.
public class Car
{
private int gear;
public Car()
{
gear = 1;
}
//Any setGear function here would be available to GearChangable and Non
}
public class SportsCar extends Car implements IGearChangable
{
public SportsCar()
{
super();
}
public void setGear(int gear)
{
//How do I access gear?
}
}
public class Van extends Car
{
public Van()
{
super();
}
//This class should have NO access to change gear
}
public interface IGearChangable
{
public void setGear(int gear);
}
I feel like I'm missing a concept. Should sport car have its own private gear? That doesn't seem right to me either.
Upvotes: 0
Views: 159
Reputation: 11386
Why do not simple move the field "gear" into the SportsCar? If the van cannot change the gear value, why should it have a field?
If the Van must have a read-only gear (which is always "1" in your case), define the abstract method getGear() in the class Car. The SportCar implements it and returns the value of the field. The Van implements it and simply returns "1".
Upvotes: 1
Reputation: 20163
Create a Transmission interface
interface Transmission {
int getGear();
}
interface Car {
}
Then create an abstract base class:
public abstract class AbstractCar implements Car {
//...
}
public abstract class AbstractManualCar implements Car, Transmission {
private int gearNum;
public AbstractManualCar() {
gearNum = 0;
}
public void setGear(int gearNum) {
this.gearNum = gearNum;
}
public int getGear() {
return gearNum;
}
}
Then a Van
extends AbstractCar
and a SportsCar
extends AbstractManualCar
.
As my seven-year-old would say, "Easy peasy, lemon squeezy." :)
Upvotes: 2
Reputation: 12042
Variables that are declared private
can be accessed outside the class. if public getter methods are present in the class.
create the get method in the car class to get the value of the private variable of the gear
like
public int getgear(){
return gear;
}
Upvotes: 0