Saturday 31 January 2015

Chapter 2.3 : Java Class & Object




Class is a template for creating objects which defines its state and behaviour. A class contains field and method to define the state and behavior of its Object. 

Syntax for Declaring Class:

<Access Modifier> class <Class_Name> extends
                 <Super_Class_Name> implements <Interface_Name>
Access modifier define who in java world can access this Class and member of the class.
Class_Name
Unique name for the class in specific package.
Super_Class_Name
Name of class which above class extends.(Super class of the given class)
Interface_Name
Name of Inerface ‘Class_Name‘ class implements.(Implements keyword is used for this purpose)

Internal structure of Class

<Access Modifier> class <Class_Name> extends <Super_Class_Name> implements <Interface_Name>{
    <static initilizar block>
    <ananymous block>
    <constructor declarations>
    <field declarations (Static and Non-Static)>
    <method declarations (Static and Non-Static)>
    <Inner class declarations>
    <nested interface declarations>
    Access variables inside class
}


 

Example of  Java Class

Classes are written in Java source file. A source file can contain more then one Java class. Below are the rules related to Java source code file.
/*
* This is Multi Line Comment and Comment can appear at any place
*/
package com.jbt;

import java.lang.*;

/*
* As this file contains public class. Then the name of this file should be TestClass.java
*/
public class TestClass {
    public int i;
    static {
        System.out.println("This is static block");
    }

    {
        System.out.println("This is ananuymous block");
    }

    TestClass() {
        System.out.println("This is constructor");
    }

    void methid() {
        System.out.println("This is method");
    }

}

class AnotherClass {
}

No comments:

Post a Comment