Jayaprakash Pujari
Jayaprakash Pujari

Reputation: 11

What should be the file name?

class Outer1{
    private static void outerMethod(){
        System.out.println("inside outerMethod");
    }
    static class Inner{
        public static void main(String[] args){
            System.out.println("inside inner class method");
            outerMethod();
        }
    }
}

I'm trying to execute this program via Command prompt. What should be the name of the file? I tried both 'Outer1' and 'Inner'. Should I make any changes in this program?

Upvotes: 0

Views: 558

Answers (4)

Sohel Shaikh
Sohel Shaikh

Reputation: 408

A static class i.e. created inside a class is called the static nested class in java. It cannot access non-static data members and methods. It can be accessed by outer class name.

  1. It can access static data members of the outer class including private.
  2. The static nested class cannot access non-static (instance) data member or method.

    class Outer1{
        private static void outerMethod(){
            System.out.println("inside outerMethod");
    }
    static class Inner{
        void msg (){
            System.out.println("inside inner class method");
            outerMethod();
        }
    }
        public static void main(String[] args) {
            Outer1.Inner obj = new Outer1.Inner();
            obj.msg();
        }
    }
    

You can learn more here.

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

File name e.g. Foo.java means that following class must be declared in it:

public class Foo {
    public static void main(String... args) {}
}

Upvotes: 0

Ravi S.
Ravi S.

Reputation: 68

If your class in not public then File Name is not matter for Compilation but In case of Program execution you should use Both class name because your using Inner class.

for example: if your filename is Outer1.java javac Outer1.java, for execution you should use this java Outer1$Inner

try this.

Upvotes: 0

JB Nizet
JB Nizet

Reputation: 691735

It should be

java Outer1$Inner

Note that this is not a file name. It's a fully qualified class name.

But really, you're making your own life more complex than necessary. Just don't use nested classes when you don't need to.

And always put your classes in a package, and indent your code, too.

Upvotes: 1

Related Questions