java - access of protected field from other class -
for below code, can access protected fields of seatplan
class , change value classroom
class, looks not secure data.
is normal? isn't protected fields can accessed subclass only? otherwise need change them private
field?
let's have abstract
class protected
fields:
public abstract class seatplan { protected int rownum; protected int columnnum; public abstract void method(); }
then 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 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 value ------ //omitted code }
i think confusing c# java.
in c#, protected
stuff can accessed subclasses. in java, protected
stuff can accessed in same package or in subclass.
that's why can change value of seat plan classroom.
is not secure?
imo, is. don't think should change row , column number of seat plan.
how make it's secure?
you should redesign seat plan class. here's 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 rownum , colnum here //but i'm lazy did not public static final seatplan plan_a = new seatplan(10, 7); public static final seatplan plan_b = new seatplan(7, 15); }
Comments
Post a Comment