构造方法实验代码

package com.imooc;

public class Telphone {
    float screen;
    float cpu;
    float mem;
    
    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);
    }

}

 

posted on 2016-04-10 15:56  Mountain's_blog  阅读(314)  评论(0编辑  收藏  举报

导航