For the below code, I can access the protected fields of a SeatPlan
class and change its value from the Classroom
class, which looks like not secure for those data.
Is this normal? Isn't it protected fields can be accessed by its subclass only? Otherwise I need to change them to private
field?
Let's say I have an abstract
class with protected
fields:
public abstract class SeatPlan {
protected int rowNum;
protected int columnNum;
public abstract void method();
}
Then it has child classes:
public class ASeatPlan extends SeatPlan {
public ASeatPlan(){ // constructor
this.rowNum= 10;
this.columnNum = 7;
}
// omitted code
}
public class BSeatPlan extends SeatPlan {
public BSeatPlan(){ // constructor
this.rowNum= 7;
this.columnNum = 15;
}
// omitted code
}
A class Room
contains a private
field of SeatPlan
object:
public class Room {
private SeatPlan seatPlan;
public Room(SeatPlan seatPlan){ // constructor
this.seatPlan = seatPlan;
}
public SeatPlan getSeatPlan(){ // getter method
return seatPlan;
}
//omitted code
}
public class Classroom {
public SeatPlan doSomething(Room room){
SeatPlan seats = Room.getSeatPlan();
seats.rowNum = 99999; <--------------- accidentally change the value ------
//omitted code
}