想要静态但不能支持?

如何解决想要静态但不能支持?

我正在尝试创建一个同时显示信息的随机汽车发电机。我以为在 randomCar 部分之前我拥有一切。它说

'com.company.Main.this' 不能从静态上下文中引用

return 中的 switch 语句下。有没有想过我可能哪里出错了?

 package com.company;
 
public class Main {
 
    class Car{
        private String name;
        private boolean engine;
        private int cylinders;
        private int wheels;
 
        public Car(String name){
            this.name = name;
        }
 
        public String getName(){
            return name;
        }
 
 
        public int getCylinders() {
            if(cylinders == 0){
                System.out.println("Unknown amount of cylinders");
            }
            return cylinders;
        }
 
        public int getWheels() {
            return wheels;
        }
 
        public boolean isEngine() {
            return engine;
        }
    }
 
    class Tacoma extends Car{
 
        public Tacoma(String name) {
            super("Tacoma");
        }
 
 
        public boolean isEngine(boolean engine) {
            return true;
        }
 
 
        public int getCylinders(int cylinders) {
            return 6;
        }
 
 
        public int getWheels(int wheels) {
            return 4;
        }
    }
 
    class Motorcycle extends Car{
 
        public Motorcycle(String name) {
            super("Harley Davidson");
        }
 
 
        public boolean isEngine(boolean engine) {
            return true;
        }
 
 
        public int getCylinders(int cylinders) {
            return 2;
        }
 
 
        public int getWheels(int wheels) {
            return 2;
        }
    }
 
    class Volvo extends Car{
        public Volvo(String name) {
            super("Volvo");
        }
 
 
        public boolean isEngine(boolean engine) {
            return true;
        }
 
        public int getCylinders(int cylinders) {
            return 4;
        }
 
 
        public int getWheels(int wheels) {
            return 4;
        }
    }
 
 
 
    public static void main(String[] args) {
   for (int i = 1; i<6; i++){
       Car car = randomCar();
        System.out.println("Car # " + i + ":" + car.getName() + "\n" +
                "Number of cylinders: " + car.getCylinders() + "\n" +
                "Number of wheels: " + car.getWheels()+ "\n" +
                "Engine is: " + car.isEngine());
       }
    }
 
    private static Car randomCar() {
        int randomNumber = (int) (Math.random()*5) +1;
        System.out.println("Random number generated is: " + randomNumber);
        switch (randomNumber){
            case 1:
                return new Tacoma(); // This is where I am getting an error
            case 2:
                return new Motorcycle(); // This is where I am getting an error
            case 3:
                return new Volvo(); // This is where I am getting an error
        }
        return null;
    }
}

解决方法

我会从这里开始阅读:https://docs.oracle.com/javase/tutorial/java/javaOO/nested.html -> 实际上所有的章节都会对你有用:https://docs.oracle.com/javase/tutorial/java/javaOO/index.html

严格来说,要解决“无法从静态上下文中引用”的问题,您只需将类设为静态(汽车、塔科马、摩托车、沃尔沃)static class Car{

从我的角度来看,您不需要嵌套类,只需在与 Main 类相同的包中创建类,就可以了(随意创建更多包以更好地构建类)

>

另外,我假设您的代码正在进行中,因为它存在多个问题:

  • 像这样的方法没有意义 public boolean isEngine(boolean engine) {return true;} 你收到一个你忽略的参数并返回一个常量值:true;我假设您在这里想要做的是拥有不同类型的汽车,每种汽车都有自己的预定义特征,但为此您应该为父级 Car 中的属性设置值。为此,您可以定义受保护的 setter,使字段受保护,或者最好创建接受所有值的构造函数
        public Car(String name,boolean engine,int cylinders,int wheels) {
            this.name = name;
            this.engine = engine;
            this.cylinders = cylinders;
            this.wheels = wheels;
        }

你可以在塔科马吃

        public Tacoma(String name) {
            super(name,true,6,4);
        }
  • 运行你的代码,我得到了 randomNumber 5 以便返回 null 并得到一个 NPE,我假设工作正在进行中
  • 在您的 switch 中,您正在调用默认构造函数 new Tacoma() 但是它不再可用,因为您定义了一个带参数的构造函数,使用可用的构造函数或创建无参数构造函数。

关于 OOP 原则还有其他问题,所以我建议再次阅读它们,只需谷歌“java OOP 原则”然后“SOLID”......那里有很多很棒的资源,你只需要时间和耐心会到的!

,

当您将 Car 类定义放入 Main 的类定义中时,您将 Car 设为内部类,因此 Car 需要外部类 Main 实例。静态方法中没有 Main 实例,没有它你就不能创建 Car。

有一个直接的解决方法:在 Car 类中添加关键字 static:

sudo npm install -g @angular/cli

这意味着没有到封闭对象的链接。

但是将其设为嵌套类没有任何好处,最好不要在开始时将一个类定义放在另一个类中。

,

您定义的内部类是 instance 成员,这意味着它们属于 static class Car { 的特定实例,因此不能从 Main 上下文中引用没有 static 实例。解决此问题的最简单方法是声明所有内部类 Main

,

首先,要解决您的错误:'com.company.Main.this' cannot be referenced from a static context,将所有方法设为静态:

static class Car{//code here} 
static class Volvo extends Car{//code here}
static class Tacoma extends Car{//code here}
static class Motorcycle extends Car{//code here}

每当您看到该错误时,就意味着一个静态方法正在调用一个非静态方法。因此,只需使两者都非静态或两者都静态。唯一的例外是 public static void main(String[] args);,它必须static

解决原始错误后,还有更多要调试的:

'Volvo(java.lang.String)' in 'com.company.Main.Volvo' cannot be applied to '()'

'Motorcycle(java.lang.String)' in 'com.company.Main.Motorcycle' cannot be applied to '()'

'Tacoma(java.lang.String)' in 'com.company.Main.Tacoma' cannot be applied to '()'

这意味着您的方法 Tacoma()Volvo()Motorcycle() 需要参数 String name。所以你所要做的就是给他们一个名字:在这里,它是

`new Tacoma("cool")`



new Volvo("car")



new Motorcycle("harley davidson")`

最后,在解决了静态和参数问题后,您得到了一个 NullPointerException,因为 randomCar() 返回 null。您的方法 Car randomCar(),表明它将返回一个Car,但是返回语句是return null;。因此,出于我们的目的,只需在此处返回 Car - rtn

private static Car randomCar() {
        int randomNumber = (int) (Math.random()*5) +1;
        System.out.println("Random number generated is: " + randomNumber);
        Car rtn = null;
        switch (randomNumber){
            case 1:
                rtn =  new Tacoma("cool"); // This is where I am getting an error
            case 2:
                rtn =  new Motorcycle("harley davidson"); // This is where I am getting an error
            case 3:
                rtn = new Volvo("car"); // This is where I am getting an error
        }
        return rtn;
    }

这不是调试您的代码所需的全部,但这是一个开始:这是系统到目前为止所做的:

Random number generated is: 3
Unknown amount of cylinders
Car # 1:Volvo
Number of cylinders: 0
Number of wheels: 0
Engine is: false
Random number generated is: 5

万岁! 这有帮助吗?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-