//大家好!类中方法返回对象是否破坏封装原则?先看以下代码:
//Map 中含有Point类对象,Map有一方法getPt()返回Point对象
//file Point.java
public class Point
{
private int x;
private int y;
public int getX()
{
return x;
}
public int getY()
{
return y;
}
public void setX(int x)
{
this.x = x;
}
public void setY(int y)
{
this.y = y;
}
}
//file Map.java
public class Map
{
private Point pt;
public void setPt(Point pt)
{
this.pt = pt ;
}
public Point getPt()
{
return pt;
}
}
//file TestMap.java
public class TestMap
{
public static void main(String [] arg)
{
Map mp = new Map();
Point pta = new Point();
pta.setX(5);
pta.setY(10);
mp.setPt(pta);
System.out.println( "before chage map 's point is: ");
System.out.println(mp.getPt().getX() + ", " + mp.getPt().getY());
Point ptb = mp.getPt();
ptb.setX(1);//此处直接用返回的对象引用改变类Map中的Point;
ptb.setY(1);
System.out.println( "after chage map 's point is: ");
System.out.println(mp.getPt().getX() + ", " + mp.getPt().getY());