Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the 3 different contexts a class can be declared?

Tags:

java

oop

class

I am told there are three different contexts in which a class can be declared in Java.
It has to do with the location within a program, but I can't think of what they are.

Obviously a class can be declared at the top of a page, the only other example I can think of is like a nested class?
I feel I may be going about this the wrong way.

like image 511
srasmus97 Avatar asked Jan 01 '23 14:01

srasmus97


1 Answers

In a package

package com.example.mypackage;

public class TheClass {
}

In a class

package com.example.mypackage;

public class OuterClass {
    class InnerClass {
    }
}

Anonymously

public class MainClass {
    public static void main(String[] args) {
        AbstractClass myObject = new AbstractClass() {
            // overrides and other fields of the
            // anonymous class goes in this block
        };
    }
}

EDIT: As @daniu stated in the comment, a class can also be created in a method:

public class MainClass {
    public static void main(String[] args) {
        class MethodClass {
        }
        MethodClass myObject = new MethodClass();
    }
}
like image 200
sweet suman Avatar answered Feb 22 '23 04:02

sweet suman