java: non-static variable this cannot be referenced from a static context

Viewed 8684

I have error java:

non-static variable this cannot be referenced from a static context

when compiling the code in line

Man m1 = new Man("a1", "b1", 11); 

How to fix that?

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;
        }
    }
    }
}

or more simply (mycompiler.io fiddle)

class HelloWorld {

    public static void main(String[] args) {
        new Tester("hello");
    }
    
    class Tester {
        public Tester(String s) { }
    }
}
2 Answers
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;
        }
    }
}
Related