package com.immoc;
import com.immoc.Telphone;
public class Telphone{
private float screen;//屏幕大小
private float cpu;
private float mem;//内存大小
public Telphone(float newScreen,float newCpu,float newMem){
screen=newScreen;
cpu=newCpu;
mem=newMem;
}
public static void main(String[] args) {
Telphone phone2=new Telphone(5.0f,1.4f,2.0f);
phone2.cpu=6.0f;
System.out.println("screen:"+phone2.screen);
System.out.println("cpu:"+phone2.cpu);
System.out.println("mem:"+phone2.mem);
}
}
请问一下 如果我对三个成员变量用以private修饰,为何我在main函数中修改cpu指为6.0f,为何属性直接修改了,难道我封装操作的不对吗????? 求哥哥姐姐解答我的困惑ioioioio~~
public class Telphone{ private float screen;//屏幕大小 private float cpu; private float mem;//内存大小 public Telphone(float newScreen,float newCpu,float newMem){ screen=newScreen; cpu=newCpu; mem=newMem; } public static void main(String[] args) { Telphone phone2=new Telphone(5.0f,1.4f,2.0f);//按照参数创建了一个对象,赋初值 phone2.cpu=6.0f; //修改cpu参数属性,此时cpu=6.0,screen=5.0,mem=2.0 System.out.println("screen:"+phone2.screen); System.out.println("cpu:"+phone2.cpu); System.out.println("mem:"+phone2.mem); } }
运行结果:
screen:5.0
cpu:6.0
mem:2.0
phone2.cpu=6.0f; 如果你想这句代码不能被执行,也就是手机new出来后不能修改cpu型号,cpu应该是final常量