Friday 16 January 2015

A Simple Example with a Class and 1 Object

As I am a retired COBOL programmer, I don’t know anything about Object Oriented programming so please forgive me if this example seems a bit elementary. Classes are templates for real-life objects. In the example below, a Rectangle class is created. Each object in this class (i.e. each rectangle) has a width and a height. These are called instance variables. An object called my_rectangle is created in the Rectangle class and its width and height are supplied. Finally, a variable called area is created, calculated and displayed:
 
Java > cat Rectangle.java
class Rectangle
  {
  double width;
  double height;
  }
class RectangleExample
  {
  public static void main(String args[])
    {
    Rectangle my_rectangle = new Rectangle();
    double area;
    my_rectangle.width = 3;
    my_rectangle.height = 4;
    area = my_rectangle.width * my_rectangle.height;
    System.out.println("Area = " + area);
    }
  }
Java > javac Rectangle.java
Java > java RectangleExample
Area = 12.0
Java >