Reputation: 177
is it any different to inheriting from a normal superclass that can be implemented?
atm I have an abstract class called abstractcar
and I have bigcar
/ smallcar
extending this abstract class
.
public abstract class AbstractCar{
private int capacity;
}
class BigCar extends AbstractCar{}
class SmallCar extends AbstractCar{}
one of the fields in abstractcar is set as "private int capacity"
but in the subclass "smallcar" when I type "capacity" as a variable to be used in the constructor, it says "capacity has private access in abstractcar"
I thought that :
fields are always private and
a subclass inherits all fields and methods of superclass?
how should I proceed now?
Upvotes: 0
Views: 713
Reputation: 5316
Instance methods and fields are inherited by the derived classes from the super
class but it does not mean they are accessible also.
Field marked as private
in super
class and inherited by sub
class is part of the object of sub
class but it is not accessible for modification in sub
class
[Non recommended solution]
Instance fields should always be declared as 'private'. Not doing so is a BAD Practice. But for understanding point of view I present below 3 points followed by recommend way.
You need to declare the field as non private so that sub class can access it.
[Recommended solution]
Add a way to set the field in super class. If the field is part of the object's life (essential field) then you can create a constructor in Super class, else you can have setter methods and can call them.
public abstract class AbstractCar{
private int capacity;
public AbstractCar(int capacity) {
this.capacity = capacity;
}
}
class BigCar extends AbstractCar{
public BigCar() {
super(6);
}
}
class SmallCar extends AbstractCar{
public SmallCar() {
super(4);
}
}
Also you can have the setter methods defined and can have protected modifier. You can call those setter methods to set the fields in super class.
Upvotes: 1
Reputation: 5591
First of all what are the difference between Abstract class and a normal class? You can not instantiate an Abstract class so it is design especially for a supper class only. A normal class can be instantiate any time.
Now inheritance, what is it? Inheritance means you can inherits all the data members and methods of an already design class into another class and utilize its functionality/behaviours as an single entity. When you inherit a supper class irrespective of whether it is a abstract or a regular class all its data members and methods inherits as it is, means all the private members as private and protective members as protective and public as public and same access mechanism will be implemented. In this case, either you have to declare data member as protective or public in supper class to directly access from sub class or otherwise you have to implement setter and getter method inside your supper class to access private members.
Upvotes: 0