主类中的每个方法都必须是静态的吗? [英] Does every method in main class have to be static?

查看:154
本文介绍了主类中的每个方法都必须是静态的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是java的总菜鸟,但今晚练习时我发现,使用OOP设计,主类中的每个方法都必须是静态的吗?在这段代码中,我无法在类中调用非静态的方法。

I'm a total noob at java, but while practicing tonight it occurred to me that with OOP design every method in the main class is going to have to be static right? In this code there is no way for me to call a method within the class that isn't static.

似乎我可能忽略了为什么要声明一个静态类的原因。谢谢你的帮助!

It seems like maybe I'm missing the point of why you would declare a class static or not. Thanks for your help!

public class JavaApplication2 {

private static CreateCar Vroom;
private static Limo Fuuu;

public static void main(String[] args) {
     Vroom = new CreateCar();
     Vroom.creator();
     getGas();
     addGas();
     getGas();
     Fuuu = new Limo();
     Fuuu.creator();
     Fuuu.wheels = 5;
     Fuuu.wheelie();
}
 public static int getGas(){
     Vroom.returnGas();
     return 0;
 }
 public static void addGas(){
     Vroom.fillerUp();
 } 
}


推荐答案

你可以调用非静态方法,但只能通过对象来实现。也就是说,您需要在给定对象上调用该方法。

You can call non-static methods, but you can only do so through an object. That is, you need to call the method on a given object.

您的主类也可以实例化,因此主类中的每个方法都不需要是静态的。
例如:

Your main class can also be instantiated, so not every method in the main class needs to be static. For example:

public class MainClass {
    int value;

    public void printValue() {
        System.out.println("" + value);
    }

    public static void main(String[] args){
        MainClass o = new MainClass();
        o.printValue();
    }
}

这篇关于主类中的每个方法都必须是静态的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆