Main Menu

search

You are here

Calling a class from within another class:

[last updated: 2019-06-13]
go to: Java
go to: Java Notes
-----

  • Suppose you create two class files (ie. compiled from their source files)
    that are in the same directory (for simplicity of avoiding dealing with (go to:) importing etc.)
  • One of them (for this example I'll call it 'InnerClass') will be the one that holds the data,
    in a variable named 'x':
    • public class InnerClass {
         int x = 5;
      }
      -------------------------
  • The other one (for this example I'll call it 'OuterClass') will be the one that gets executed,
    ie. it has a 'main' method:
    • class OuterClass {
         public static void main(String[] args) {
            InnerClass newObj = new InnerClass();
            // This line creates a new instance of class InnerClass,
            // and this new instance is named newObj.
            System.out.println(newObj.x);
         }
      }
      -------------------------

.

.

.

eof