简体   繁体   中英

Why can't we use this instance in the static method of extended class?

Base class

class Basics415 {   

    Basics1 b1 = new Basics1();

    public static void main_hooo(){
        out.println("1234");     
    }

    void main_ho(){

    }

}

Extended class

public class Basics5 extends Basics415{     

    public static void main(String[] args){

        this.main_hooo();  // this line throws error.
    }

}

Why we aren't able to use this instance inside a static method of the extended class?

Your main method is static, which means there is no instance of Basic associated with it so this won't work. To access the static methods of Basics415 , you should refer to them explicitly like this:

public class Basics5 extends Basics415{
    public static void main(){
        Basics415.main_hooo();
    }
}

You could also just do this since Basic5 extends Basic415 . Both are acceptable, but your org may have their own style guidelines:

public class Basics5 extends Basics415{
    public static void main(){
        main_hooo();
    }
}

That is not the correct way to access a static method. this is not static. Instead do Basic5.main_hooo()

this和static彼此相反,就这么简单。如果要使用它,请在非静态方法中使用它。

The main() method must be defined with a String[] parameter if you want it to execute first. Also, main() is a static method (it belongs to the class). There is no instance (this) to refer to.

Use the class name to call it within main:

Basics415.main_hooo();  // this line no longer throws an error.

For static method not require create an object,

    public static void main(String[] args) {
        Basics415 b = new Basics415();
        b.main_hooo();// output : 1234
        main_hooo();// output : 1234
        Basics415.main_hooo();// output : 1234
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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