I'm currently in a Java-based university class and for coding samples the professor is using protected
fields for the subclasses to access.
I asked if this was bad practice and was told it is normal. Is this true, why not use setters and getters for abstract methods? I thought it was always best practice to restrict as much information as possible unless required otherwise.
I tested out using setters and getters with abstract
parent and it works fine for abstract
parent classes that are subclassed. Although abstract classes cannot be instantiated
, they can still be used to create objects when a subclass
is instantiated
as far as I understand.
Here is a short example:
public abstract class Animal {
protected int height;
}
public class Dog extends Animal {
public Dog() {
height = 6;
}
}
public class Cat extends Animal {
public Cat() {
height = 2;
}
}
As opposed to using:
public abstract class Animal {
private int height;
public getHeight() {
return height;
}
public setHeight(int height) {
this.height = height;
}
}
public class Dog extends Animal {
public Dog() {
setHeight(6);
}
}
public class Cat extends Animal {
public Cat() {
setHeight(2);
}
}