Java Classes - Why is one of these valid and one is not?

40 Views Asked by At

I'm kind of confused about how java classes work.

How come when I do this, it gives me an error that says: "Non-static variable cannot be referenced from static context":

public class Test {
    class Building {
        Building() {
            System.out.println("You've made a building");
        }
    }
    
    public static void main(String[] args) {
        Building building1 = new Building();
    }
}

But when I pull the building class out of the Test class:

public class Test {

    public static void main(String[] args) {
        Building building1 = new Building();
    }
}

class Building {

    Building() {
        System.out.println("You've made a building");
    }
}

Now it works?

Can somebody explain why #2 works but #1 doesn't?

I would expect both to work or neither to work

0

There are 0 best solutions below