从其他类访问受保护的字段

时间:2016-04-19 04:33:45

标签: java

对于下面的代码,我可以访问SeatPlan类的受保护字段,并从Classroom类更改其值,这对于这些数据看起来不安全。

这是正常的吗?是不是受保护的字段只能被其子类访问?否则我需要将它们更改为private字段?

假设我的abstract课程有protected个字段:

public abstract class SeatPlan {
    protected int rowNum;
    protected int columnNum;

    public abstract void method();
}

然后它有子类:

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
}

班级Room包含privateSeatPlan字段的字段:

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
    }

1 个答案:

答案 0 :(得分:0)

我认为你把C#与Java混淆了。

在C#中,protected内容只能由子类访问。但是在Java中,可以在同一个包或子类中访问protected个东西。

这就是为什么你可以从教室改变座位计划的价值。

这不安全吗?

IMO,它是。我认为您不应该更改座位计划的行数和列数。

如何制作以确保安全?

您应重新设计座位计划课程。这是一个粗略的想法:

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);
}