public class StaticDemo { static String str="hello"; int i=10; static void staticMethod() { System.out.println("static method"); } void non_staticMethod() { System.out.println("not static method"); staticMethod(); } public static void main(String args[]) { StaticDemo st=new StaticDemo(); st.staticMethod(); st.non_staticMethod(); System.out.println(st.i); System.out.println(StaticDemo.str); } } 写出程序的输出结果(按顺序)。
时间: 2023-12-14 14:38:16 浏览: 29
程序的输出结果为:
```
static method
not static method
static method
10
hello
```
解释:
- 在main方法中,首先创建了一个StaticDemo对象st。
- 接着,通过st对象调用staticMethod()方法,输出"static method"。
- 然后,通过st对象调用non_staticMethod()方法,输出"not static method",接着又调用staticMethod()方法,输出"static method"。
- 最后,输出st对象的属性i的值10和类属性str的值"hello"。
相关问题
@Value("${HECDPlatform.application.xssenable}") private Boolean nonStaticVar; public void nonStaticMethod() { // 非静态方法的实现 } private static Boolean staticVar; public static void staticMethod() { staticVar = new HTTPTool().nonStaticVar; // 获取注入的非静态变量 // 使用静态变量 staticVar } public static void main(String[] args) { staticVar = new HTTPTool().nonStaticVar; System.out.println(staticVar); }
这段代码看起来像是Java语言的代码片段。其中通过@Value注解获取了配置文件中的HECDPlatform.application.xssenable属性,并将其赋值给了nonStaticVar变量。另外定义了一个非静态方法nonStaticMethod和一个静态方法staticMethod,后者在方法体中使用了通过HTTPTool类获取的非静态变量nonStaticVar。最后在main方法中也获取了这个非静态变量并输出。不过,这段代码缺少完整的上下文,无法确定它的作用和用途。
Non-static method 'findUserInfoByIdAndName(java.lang.Integer, java.lang.String)' cannot be referenced from a static context
这个错误是因为你在静态方法中调用了一个非静态的方法。
静态方法是属于类的方法,可以直接通过类名调用,不需要创建类的对象。而非静态方法是属于对象的方法,需要先创建类的对象才能调用。
如果你想在静态方法中调用非静态方法,需要先创建类的对象,然后通过对象来调用非静态方法。
例如,假设你有一个类`User`,其中有一个非静态方法`findUserInfoByIdAndName(Integer id, String name)`,现在你在一个静态方法中想要调用该方法,你需要先创建`User`类的对象,然后通过对象来调用该方法,示例代码如下:
```
public class User {
public void findUserInfoByIdAndName(Integer id, String name) {
// 实现方法
}
public static void staticMethod() {
User user = new User();
user.findUserInfoByIdAndName(1, "张三");
}
}
```
在静态方法`staticMethod()`中,我们首先创建了`User`类的对象,然后通过对象来调用非静态方法`findUserInfoByIdAndName(Integer id, String name)`,这样就能避免上述错误了。