类实例化时可以不创建引用对象

1、使用构造函数初始化时,可以不创建引用对象

构造函数在new创建对象时,如果对象未使用其它变量或方法时,可以不创建引用对象

public class StaticDemo6 {

    public static void main(String[] args) {
        new Student(11, "a", 250);            //无需创建引用对象,因为没有使用实例变量或实例方法
        new Student(12, "b", 350);            //无需创建引用对象
    
        System.out.println(Student.getTotleFee());
    }
}

class Student{
    int age;
    String name;
    int fee;
    static int totalFee;                //类变量
    public Student(int age,String name,int fee) {
        this.age=age;
        this.name=name;
        this.fee=fee;
        totalFee +=fee;                //每产生一个student,就加一次fee,赋值给totalFee
    }
    public static int getTotleFee(){        //类方法,返回totalFee
        return totalFee;            
    }
}

输出:

600

posted @ 2017-02-16 15:50  自学开发的老司机  阅读(608)  评论(0编辑  收藏  举报