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:
public class MyClass {
 int x = 5;
 public static void main(String[ ] args) {
  MyClass myObj = new MyClass( );
  System.out.println( myObj.x );
 }    // Output: 5
}

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

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.
public class MyClass {
  int x = 5;
}

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

undcemcs02> javac MyClass.java
undcemcs02> javac OtherClass.java
undcemcs02> java OtherClass
5




      Two atoms are walking down the street.    
      The first one sees the second one and asks,    
      “Hey, what’s the matter? You look a little down.”    
      The second atom says, “Yeah, I lost an electron.”    
      The first atom says, “Oh man, are you sure?”    
      The second atom says, “I'm positive.”