package com.imooc; public class Telphone { private float screen; private float cpu; private float mem; public float getScreen(){ return screen; } public void setScreen(float newScreen){ screen = newScreen; } public Telphone(){ System.out.println("无参的构造方法执行了!"); } public Telphone(float newScreen, float newCpu, float newMem){ //构造方法确保赋给成员的变量的值是一个合理值 if(newScreen<3.5f){ System.out.println("您输入的参数有问题,自动赋值3.5"); screen = 3.5f; }else{ screen = newScreen; } cpu = newCpu; mem = newMem; System.out.println("有参的构造方法执行了!"); } }
package com.imooc; public class InitialTelphone { public static void main(String[] args) { // TODO Auto-generated method stub //通过无参的构造方法可以创建对象 Telphone phone1 = new Telphone(); //通过有参的构造方法可以创建对象,并给对象的实例变量赋初值 Telphone phone2 = new Telphone(1.5f, 1.4f, 2.2f); //通过setter方法修改变量的值 phone1.setScreen(5.0f); //通过getter方法获取变量的值 System.out.println("screen:" + phone1.getScreen()); } }