Java classes basics



In the Previous tutorial we have leaned basic syntax of class. In this tutorial we are going to learn actual programmatic implementation of Class using Java. Firstly read below document carefully and then follow steps given at the end of article in order too run it on your system.

Live Example : Simple Class Program [Area of Rectangle]

class Rectangle {
  double length;
  double breadth;
}

// This class declares an object of type Rectangle.
class RectangleDemo {
  public static void main(String args[]) {
    Rectangle myrect = new Rectangle();
    double area;

    // assign values to myrect's instance variables
    myrect.length = 10;
    myrect.breadth = 20;

    // Compute Area of Rectangle
    area =  myrect.length * myrect.breadth ;

    System.out.println("Area is " + area);
  }
}

Output :

C:Priteshjava>java RectangleDemo
Area is 200.0

[336×280]

Explanation : Class Concept

1. Class Creation / Declaration :

Consider following class –

class Rectangle {
  double length;
  double breadth;
}
  • class defines a new type of data.
  • Rectangle is our new data type.
  • “Rectangle” will be used to declare objects of type Rectangle.
  • class declaration only creates a template. It does not create an actual object.

2. Creation of Object

Rectangle myrect = new Rectangle();
  • Actual Creation of Object.
  • Memory is allocated for an object after executing this statement.
  • This Statement will create instance of the class “Ractangle” and name of instance is nothing but actual object “myrect“.
  • Fresh copy of Instance variables gets created for Fresh Instance. [myrect now have its own instance variables -> length,breadth ]
  • Following fig shows one unknown term – Constructor (Don’t worry about this term , you will get more details in the incoming chapters)

Creating Object of Class in Java Programmming Language

3. Accessing Instance Variables Of Object/Instance using DOT Operator

myrect.length  = 10;
myrect.breadth = 20;
  • As explained earlier , Each Instance/Object gets their own copy of instance variables i.e length and breadth.
  • We can access “myrect’s” copy of instance variable using “DOT” operator (as shown above).

[468×60]

Steps to Run Above Program

  1. Create RectangleDemo.java . [suppose your file have multiple classes then you must save file with class name that contain main class ]
  2. Copy Above Program into RectangleDemo.java and save it.
  3. Run MyRectangle.java inside Command Prompt.