Java Class: Explanation with a Program Example

Google+
Google+
http://programmingloops.com/java-class/

A Java class that initialize with class keyword is a collection of fields, constructors and methods. A single Java program can have N number of classes, and a single class can have N number of fields, constructors and methods.

A general structure of a Java class:
class (name of the class)
{
  // body of the class which includes fields, constructors and methods.
}

Java class explanation with a program example:
class A                                                       // class
{
    int a, b, c =10, d;                                                // fields
    String str;
    A()                                                        // constructor
    {
        System.out.println(“This message is from the constructor”);
    }
    void met()                                                          // method
    {
        a = 29;
        b = 23;
        d = a + b – c;
        str = “The value of A + B – C = “;
        System.out.println(str+d);        
    }    
}
class B                                            // class
{
    public static void main(String args[])
    {
        A obj = new A();
        obj.met();
    }
}

In this example, there are two classes, A and B. In class A, you can see the integer (int) data types’ fields, a constructor with the same name as of the class, and a method named as met are provided. In class B, there is a main method where an object of class A is created, and its properties are used.

Why Java class?
Java class fulfils the basic OOP’s (Object Oriented Programming) principles that are inheritance, polymorphism and encapsulation. A class inheriting the properties of the other class is called inheritance, like fields and methods. Polymorphism is a concept where a property of a class overrides or overwrites the property of the other class. Encapsulation is a concept of binding of data in a module, a class binds the fields, constructors and methods in an object.