我们可以改变全局变量this.classvariable的值吗?

时间:2017-09-30 20:35:20

标签: java

如果我在下面的Student构造函数中分配了this.bussfee = busfee,那么this.busfee变量值应该是14000.但实际上它保持相同的值 - 4000。你能帮我理解为什么吗?

public class PrintStudent {
    public static void main(String[] args) {
        //here i m calling constructor with value 14000
        Student st3=new Student("Rohit",35,14000);
        Student st4=new Student();

    }
}

public class Student { 
    //These variable are global variable 
    int Busfee; 

    protected Student () { 
        this.Busfee=4000; 
    } 

    protected Student (String Name,int Age,int Busfee) { 
        this.Name=Name; 
        this.Age=Age; 
        this.Busfee=Busfee; 
    } 
}

1 个答案:

答案 0 :(得分:0)

第二个构造函数赋值,第一个使用4000.如果你的Busfee是静态的,那么第二个会覆盖它。

以下代码的结果:

public static void main(String[] args) {
    //here i m calling constructor with value 14000
    Student st3=new Student("Rohit",35,14000);
    System.out.println(st3.Busfee);
    Student st4=new Student();
    System.out.println(st3.Busfee);
    System.out.println(st4.Busfee);
}

如果不是静态的,则打印:14000,14000,4000

如果是静态,则打印:14000,4000,4000