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

时间:2017-07-28 18:55:50

标签: java non-static

我有错误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;
    }
}
}

}

2 个答案:

答案 0 :(得分:2)

一种方法

Man类声明为静态,并且您可以在main()内访问它,这也是静态的(不依赖于类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;
        }
    }
}

答案 1 :(得分:-1)

public class Main {

    public static void main(String[] args) {
        // write your code here
        VerySimple alice = new VerySimple();
    }

    class VerySimple {
        private int age;
        private String name;
        //constructor

        VerySimple(int age, String name) {
            this.age = age;
            this.name = name;
        }

        //getter method
        int getAge() {
            return age;
        }

        //setter method
        public void setAge(int a) {
            age = a;
        }

        //getter
        String getName() {
            return name;
        }
    }
}