Java 在类(其中没有主函数的类)内使用静态方法时没有输出
这是我的主要课程:Java 在类(其中没有主函数的类)内使用静态方法时没有输出,java,function,class,methods,Java,Function,Class,Methods,这是我的主要课程: public class App { public static void main(String[] args){ Student s1=new Student(); }; }; 这是创建的类: class Student { public static void f1(){ f2(); } public static String f2(){
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”,但根本不打印输出(不打印任何内容)。有人能解释一下原因吗?f2()
正在返回字符串,但f1
没有打印它:
public static void f1(){
System.out.println(f2());
}
public static String f2(){
return "hello";
}
public Student(){
f1();
}
要在控制台日志中打印,您应该尝试:System.out.println(“Hello”)
您返回的是值,而不是打印值。打印值与返回值之间存在差异。
如果您想打印出来,您应该尝试这样做:
class Student {
public static void f1(){
f2();
}
public static void f2(){
System.out.print("hello");
}
public Student(){
f1();
}
}
您必须使用System.out.println(“Hello”)而不是返回“Hello” I方法
由于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();
}
}
II方法
你可以这样试试
class Student {
public static void f1(){
System.out.println(f2());//calling method
}
public static String f2(){
return "hello";
}
public Student(){
f1();
}}
这里没有任何东西可以打印任何东西。你的期望是没有根据的。