java:非静态变量,不能从静态上下文中引用

生殖器

我有错误Java:非静态变量,当在Man m1 = new Man(“ a1”,“ b1”,11)行中编译代码时,不能从静态上下文中引用它;如何解决?

public class Solution
{
public static void main(String[] args)
{
    //create two object of every class here
    Man m1 = new Man("a1", "b1", 11);
    Man m2 = new Man("a2", "b2", 12);
    Woman w1 = new Woman("a11", "b11", 13);
    Woman w2 = new Woman("a22", "b22", 14);

    //output them to screen here
    System.out.println(m1.name + " " + m1.age + " " + m1.address);
    System.out.println(m2.name + " " + m2.age + " " + m2.address);
    System.out.println(w1.name + " " + w1.age + " " + w1.address);
    System.out.println(w2.name + " " + w2.age + " " + w2.address);
}

//add your classes here
public class Man
{
    private String name;
    private String address;
    private int age;

    public Man(String name, String address, int age)
    {
        this.name = name;
        this.address = address;
        this.age = age;
    }
}
}

}

尼尔·阿尔法西

一种方法

Man声明为静态,您还可以从main()其中访问静态类(不与class的任何实例绑定Solution):

public static class Man

另一种方法

我们还可以让类保持Man非静态状态,并创建一个实例级工厂方法,该方法将创建以下实例Man

public class Solution {

    public static void main(String[] args) {
        //create two object of every class here
        Solution solution = new Solution();
        Man m1 = solution.createMan("a1", "b1", 11);
        Man m2 = solution.createMan( "a2", "b2", 12);

        //output them to screen here
        System.out.println(m1.name + " " + m1.age + " " + m1.address);
        System.out.println(m2.name + " " + m2.age + " " + m2.address);    
    }

    Man createMan(String name, String address, int age) {
        return new Man(name, address, age);
    }

    //add your classes here
    public class Man {
        private String name;
        private String address;
        private int age;

        private Man(String name, String address, int age) {
            this.name = name;
            this.address = address;
            this.age = age;
        }
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

java:不能从静态上下文中引用非静态变量错误

不能从静态上下文中引用非静态变量 [JAVA]

非静态变量s不能从静态上下文中引用

非静态变量,不能从静态上下文中引用

“不能从静态上下文中引用的非静态变量”?

不能从静态上下文中引用非静态变量?

非静态变量 this 不能从静态上下文中引用 Dormitory dormitory = new Dormitory();

Rectangle.java:35:错误:非静态变量,不能从静态上下文中引用

Java Blackjack 程序创建错误:不能从静态上下文中引用非静态变量

非静态变量不能从静态上下文Java中引用

创建对象时,“不能从静态上下文引用的非静态变量”

的java - 非静态方法“getLogger”不能从静态上下文中引用

非静态方法不能从静态上下文中的java 8流引用

JAVA - 不能从静态上下文中引用非静态方法 add(E)

错误:无法从Java的静态上下文中引用非静态变量扫描

非静态方法不能从静态上下文中引用

非静态方法不能从静态上下文中引用

非静态方法getIntent()不能从静态上下文中引用

不能从静态上下文中引用非静态方法 matcher(CharSequence)

非静态方法count(int)不能从静态上下文中引用

非静态类不能从静态上下文中引用

非静态方法<T> findViewById(int)不能从静态上下文中引用

不能从静态上下文中引用非静态方法“inflate(byte[],int,int)”

非静态方法readData(GoogleApiClient,DataReadRequest)不能从静态上下文中引用

试图让我的显示方法工作(不能从静态上下文中引用非静态方法)

非静态edit()不能从静态上下文中引用

不能从静态上下文中引用非静态 setGravity

不能从静态上下文中引用非静态方法 getSocketFactory

非静态方法'getSharedPreferences(java.lang.String,int)'不能从静态上下文中引用