繁体   English   中英

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

[英]Can we change value of global variable this.classvariable?

如果我在下面的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; 
    } 
}

第二个构造函数分配值,第一个构造函数使用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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM