从另一个文件的方法中检索信息

时间:2017-12-30 09:18:41

标签: java methods

我试图从HelloWorld.java中的newhello.java调用rtnval

这些是我得到的错误

错误:(9,27)java:找不到符号   符号:方法newhello()   location:类HelloWorld

错误:(10,28)java:找不到符号   符号:方法newval()   location:类HelloWorld

public class HelloWorld {

    public static void main (String[] args){
        System.out.println("Test");
        int fnum1 = addition(8,2);
        System.out.println(fnum1);
        int fnum2 = subtract(2,8);
        System.out.println(fnum2);
        newhello newval = newhello();
        System.out.println(newval());
    }
    public static int addition (int num1, int num2){
        int total;
        total = num1 + num2;
        return total;
    }
    public static int subtract (int num1, int num2){
        int total;
        total = num1 - num2;
        return total;
    }
}
public class newhello extends HelloWorld {
    public static void main (String[] args){
        System.out.println(rtnval());
    }
    public static String rtnval (){
        String msg;
        msg = "Test";
        return msg;
    }
}

我的印象是我不得不为它调用实例然后以那种方式使用它?

2 个答案:

答案 0 :(得分:0)

newhello();指的是当前班级中的newhello()方法 它不存在。

  

我的印象是我必须为它调用实例   用那种方式??

事实上,您不需要创建newhello实例,因为rtnval是静态方法。
所以就这样做:newhello.rtnval();

请注意,在Java中,类名应以大写字母开头并使用camelcase 例如,根据命名约定,开发人员期望对变量进行实例方法调用:

newhello.rtnval();

在这里,我们希望进行static方法调用:

Newhello.rtnval();

所以NewHello是一个更好的类名。

答案 1 :(得分:0)

你把它变成了一个静态方法所以只需要调用:

newhello.rtnval();

但是在创建实例时你也犯了一个错误。而不是:

newhello newval = newhello();

您需要使用关键字new来制作新实例!

newhello newval = new newhello();

事情是......我看到你最不懂Java。你有2个主要方法,没有使用new关键字等等......在尝试让自己的程序看一些教程之前。在我学习的时候,我一直被困在同一件事上。不想看教程。我将为您链接一些很棒的教程:

https://www.youtube.com/watch?v=Hl-zzrqQoSE&list=PLFE2CE09D83EE3E28

祝你好运!