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

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

原文地址:https://www.cnblogs.com/ibelieve618/p/6406097.html