I am currently participating in a university class in Java, and for coding samples, the professor uses fields protectedto access subclasses.
I asked if it was bad practice, and she was told that it was normal. That's true, why not use setters and getters for abstract methods? I thought it was always best to limit as much information as possible, unless otherwise required.
I tested using setters and getters with a parent abstract, and it works great for parent classes abstractthat are subclasses. Although abstract classes cannot exist , instantiatedthey can still be used to create objects, if subclassany instantiated, as I understand it.
Here is a quick 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;
}
}
In contrast to use:
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);
}
}
source
share