Introduction to Java Classes

This tutorial will take you step by step in uderstanding the basics of a class , how to define it and how to use it. The best way to learn is to compile and run these programs yourself (copy, paste, compile and run !). Comments such as /* this is a comment */ or // this is another comment are inserted to explain what does the line of code do. The programs are kept simple for the purpose of concentrating on the main idea in question.

Example 1: simple class

 

// this class is called Room1
class Room1{ 

// it defines 3 instance variables: length, width and height 
   double length;
   double width;
   double height;

   public static void main(String t[]){
   }
}
      

The above program defines a template for the class Room1, no object of type Room1 is created yet.

Example 2: how to create an object of type Room1 ?

  
class Room1{ 

   double length;
   double width;
   double height;

   public static void main(String t[]){

// this statement creates an object of type Room1 and myroom1 is
// an instance of Room1.
   Room1 myroom1 = new Room1();

// this assigns values to the instance variables length, 
// width and height of the object referenced by myroom1.
   myroom1.length= 10.0; // Note the use of the dot(.) operator.
   myroom1.width = 8.0;
   myroom1.height = 5.5;

// this creates another object of type Room1.
   Room1 myroom2 = new Room1();

// this assigns values to the instance variables length, 
// width and height of the object referenced by myroom2.
   myroom2.length= 9.0;
   myroom2.width = 7.0;
   myroom2.height = 4.5;
   }
}   

You can create as many objects as you wish and assigns to each one of them different values of the instance variables as we have seen above. Note that each object has its own copies of the instances variables assigned.
 

Do you have a Java Problem?
Ask It in The Java Forum

Java Books
Java Certification, Programming, JavaBean and Object Oriented Reference Books

Return to : Java Programming Hints and Tips

All the site contents are Copyright © www.erpgreat.com and the content authors. All rights reserved.
All product names are trademarks of their respective companies.
The site www.erpgreat.com is not affiliated with or endorsed by any company listed at this site.
Every effort is made to ensure the content integrity.  Information used on this site is at your own risk.
 The content on this site may not be reproduced or redistributed without the express written permission of
www.erpgreat.com or the content authors.