-5

Why i cant even instantiate the object? I am confused am i creating the object in a wrong way?

class Main {

    public class Age {
        public int years = 1;

        public Age(int y) {
            years = y;
        }

        public void print() {
            System.out.println(years);
        }
    }

    public static void main(String[] args) {
        Age four = new Age(4); age = four;
        age.years++;
        four.print();
    }
}
ZAX9732
  • 85
  • 6

1 Answers1

2

Your nested class Age is non static, which means you need an instance of the main class to reference Age. Either define Age as static, or create a new Main object.

    public static void main(String[] args) {
        Age four = (new Main()). new Age(4); 
        Age age = four;
        age.years++;
        four.print();
    }

Java inner class and static nested class

Edit:

Or declare it outside Main, not a nested class.

Martin'sRun
  • 522
  • 3
  • 11