随笔 - 20  文章 - 57  trackbacks - 0
<2024年4月>
31123456
78910111213
14151617181920
21222324252627
2829301234
567891011

常用链接

留言簿(2)

随笔分类

随笔档案

文章分类

文章档案

51CTO

搜索

  •  

最新评论

阅读排行榜

评论排行榜


     构造方法
     构造方法是一种特殊的方法,没有返回值,函数名必须与类名相同。
     一个类里可以创建多个构造方法,如果不创建,系统会自动创建一个空的没有参数的构造方法。下面由一个例子来说明构造方法中参数不同时的作用:



class Employee{
    //设置Employee类的属性
    private int id;
    private String name;
    private double price;
    private String branch;
    //无参的构造方法
    Employee(){
        System.out.println("设置无参信息");
    }
    //可不可以把判断输入信息的方法写到构造函数中?
    Employee(int id){
        if(this.id>0)
        {
            this.id = id;
            System.out.println("设置单参信息    " + this.id);
        }
        else{
            System.out.println("输入有误!");
        }
       
    }
    Employee(int id, String name){
        this.id = id;
        this.name = name;
        System.out.println("设置双参信息    " + this.id + "   " + this.name);
    }
   
    Employee(int id, String name, double price, String branch){
        //在这个构造方法中,JVM会先调用setId方法来给id属性数值
        this.setId(id);
        this.setBranch(name);
        this.setPrice(price);
        this.setBranch(branch);
       
//        this.id = id;
//        this.name = name;
//        this.price = price;
//        this.branch = branch;
        System.out.println("设置四参信息    " + this.id + "   " + this.name + "  " + this.price + "  " + this.branch);;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public double getPrice() {
        return price;
    }
    public void setPrice(double price) {
        this.price = price;
    }
    public String getBranch() {
        return branch;
    }
    public void setBranch(String branch) {
        this.branch = branch;
    }





public class Workers {
    public static void main(String[] args){
        //声明一个对象,并实例化
        Employee employee1 = null;
        System.out.println("******************************");
        employee1 = new Employee();
        Employee employee2 = new Employee(-2010);
        Employee employee3 = new Employee(2010, "员工");
        Employee employee4 = new Employee(2010, "员工2", 45000, "技术部");
    }

}

这个程序的输出结果是:
                   ******************************
                   设置无参信息
                   输入有误!
                   设置双参信息    2010   员工
                   设置四参信息    2010   null  45000.0  技术部


这个程序能够说明,构造方法是在一个对象被实例化的时候被调用的。

在构造方法中,我还有个问题:
              可不可以把判断输入信息是否正确的方法写到构造函数中?
              判断输入信息是否正确写在set方法中和写在构造方法中有什么不同的效果。

      以下是我自己的看法不知道是否正确?
              我觉得把判断信息写在构造方法中和set方法中的作用是一样的,只不过写在set方法中必须把构造方法中的赋值语句由this.属性名=属性名   换为  this.set属性名(属性名)就可以了!


               但不知道这样做可不可以,从程序上来说是可以的,但在实际中这样做是否可行,还请大虾们指教。

             
posted on 2010-10-14 00:52 tovep 阅读(804) 评论(0)  编辑  收藏

只有注册用户登录后才能发表评论。


网站导航:
 
主页