javanon-static

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


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) { }
    }
}

Solution

  • One approach

    Declare Man class as static and you'll be able to access it from within main() which is static as well (not tied to any instance of class Solution):

    public static class Man

    Another approach

    We can also leave class Man non-static and create an instance-level factory-method which will create instances of 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;
            }
        }
    }