1

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
    }
mmcc88
  • 177
  • 1
  • 10
  • 2
    Possible duplicate of [Difference among 'public', 'default', 'protected', and 'private'](http://stackoverflow.com/questions/215497/difference-among-public-default-protected-and-private) – Savior Apr 19 '16 at 04:34
  • You need to understand access modifiers. A simple tutorial can be found here: http://www.tutorialspoint.com/java/java_modifier_types.htm A simple solution for your code it's the the best solution, as you will need to know how to use the modifiers for every single Java project. – goncalopinto Apr 19 '16 at 04:55

1 Answers1

0

I think you are confusing C# with Java.

In C#, protected stuff can only be accessed by subclasses. But in Java, protected stuff can be accessed in the same package or in a subclass.

That's why you can change the value of the seat plan from a classroom.

Is this not secure?

IMO, it is. I don't think you should change the row and column number of a seat plan.

How do I make it so that it's secure?

You should redesign your seat plan class. Here's a rough idea:

public final class SeatPlan {
    private SeatPlan(int rowNum, int colNum) {
        this.rowNum = rowNum;
        this.colNum = colNum;
    }

    private int rowNum;
    private int colNum;

    //You should add getters for rowNum and colNum here
    //But I'm lazy so I did not do it for you

    public static final SeatPlan PLAN_A = new SeatPlan(10, 7);
    public static final SeatPlan PLAN_B = new SeatPlan(7, 15);
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313