Classes and Objects (Cont.)


Creating an Object
A class is a template or blueprint from which objects are created, and an object is the instance (result) of a class.

In Java, an object is created from a class. To create an object of MyClass, specify the class name, followed by the object name, and use the keyword new:
1public class MyClass {
2 int x = 5;
3 public static void main(String[ ] args) {
4  MyClass myObj = new MyClass( );
5  System.out.println( myObj.x );
6 }   // Output: 5
7}

Creating Multiple Objects
You can create multiple objects of one class:
1public class MyClass {
2  int x = 5;
3  public static void main( String[ ] args ) {
4    MyClass myObj1 = new MyClass( );  // Object 1
5    MyClass myObj2 = new MyClass( );  // Object 2
6    System.out.println( myObj1.x );   // Output: 5
7    System.out.println( myObj2.x );   // Output: 5
8  }
9}

Using Multiple Classes
You can also create an object of a class and access it in another class. This is often used for better organization of classes (one class has all the attributes and methods, while the other class holds the main() method). The example creates two files in the same directory/folder: MyClass.java and OtherClass.java.
1public class MyClass {
2  int x = 5;
3}

1class OtherClass {
2  public static void main( String[ ] args ) {
3    MyClass myObj = new MyClass( );
4    System.out.println( myObj.x );
5  }   // Output: 5
6}

1undcemcs02> javac MyClass.java
2undcemcs02> javac OtherClass.java
3undcemcs02> java OtherClass
45