java—在类(没有主函数的类)中使用静态方法时没有输出

n7taea2i  于 2021-07-06  发布在  Java
关注(0)|答案(5)|浏览(349)

这是我的主要课程:

public class App {
    public static void main(String[] args){
        Student s1=new Student();

    };
    };

这是创建的类:

class Student {
    public static void f1(){
        f2();
    }
    public static String f2(){

        return "hello";
    }
    public Student(){
        f1();
    }

}

现在,因为我在main类中创建了一个对象s1,所以调用了构造函数,它有f1(),所以调用了f1(),现在f1()有f2(),所以调用了f2(),所以我认为必须打印“hello”,但是输出根本没有打印(没有打印任何内容)。有人能解释一下原因吗?

jm81lzqq

jm81lzqq1#

f2() 正在返回 String ,但是 f1 不打印:

public static void f1(){
    System.out.println(f2());
}
public static String f2(){    
    return "hello";
}
public Student(){
    f1();
}
nszi6y05

nszi6y052#

我的方法。。。。
由于f2方法有一个返回类型,为了获得从中获得的值,请对与返回类型兼容的类型进行引用,并使用相同的引用代码编写单词hello,如下所示

class Student {
public static void f1(){
    String x=f2(); //method calling
    System.out.println(x);

}
public static String f2(){

    return "hello";
}
public Student(){
    f1();
}

}
二、方法。。。。。。
你可以这样试。。。

class Student {
public static void f1(){

    System.out.println(f2());//calling method

}
public static String f2(){

    return "hello";
}
public Student(){
    f1();
}}
rqdpfwrv

rqdpfwrv3#

要在控制台日志中打印,您应该尝试:system.out.println(“hello”);
您正在返回值而不是打印它。

d6kp6zgx

d6kp6zgx4#

必须使用system.out.println(“hello”)而不是返回“hello”;

b5lpy0ml

b5lpy0ml5#

打印和返回值是有区别的。如果你想把它打印出来,你应该尝试这样做:

class Student {
    public static void f1(){
        f2();
    }
    public static void f2(){

        System.out.print("hello");
    }
    public Student(){
        f1();
    }

}

相关问题