Software & Finance





Java - Class





In Java, class is a keyword. Using class, we can implement all object oriented programming language concepts. All the members declared in Java classes are private with provides access to the package by default. We can also have protected access level to for derived classes and public access level for any functions or classes.

Three access levels are,

1. Private - Can be accessed only by the members of the class
2. Protected - Can be accessed by the struct and its derived class (subclass) and the package.
3. public - Can be accessed by any class, subclass and the package.

4. No modifier - Can be accessed only by the membes of the class and the package.

 

In Java you do not need to use any keyword like virtual or override since by default all non static functions are considered as virual. You have to make it either private or use final keyword to remove the default virtual feature in each function in the Java classes.

 

There are 3 classes given on this example. Shape is a base class and Circle and Triangle are the classes derived from the base class Shape. The base class Shape is used to access all two dervied class functions.

 

NOTE: No virtual or override keyword in Java.

 

 

Source Code


import java.io.*;

 

 

class Shape

{

 

    public Shape()

    {

        System.out.println("Shape");

    }

 

    public void draw()

    {

        System.out.println("Drawing Shape");

    }

}

 

 

class Circle extends Shape

{

    int r;

 

    public Circle()

    {

        System.out.println("Circle");

    }

 

    public void draw()

    {

        System.out.println("Drawing Circle");

    }

}

 

 

 

class Triangle extends Shape

{

    public int a,b,c;

 

    public Triangle()

    {

        System.out.println("Triangle");

    }

 

    public void draw()

    {

        System.out.println("Drawing Triangle");

    }

}

 

class MyClass

{

    public static void main(String[] args)

    {

            Shape[] objects = { new Shape(),

                                    new Circle(),

                                    new Triangle()

                  };

 

        System.out.println("\n\nNow Drawing Objects\n");

 

            for(int i = 0; i < 3; i++)

                  objects[i].draw(); // // This line explains the concept of polymorphism

       

 

        System.out.println("\n");

    }

}

Output


D:\Program Files\Java\jdk1.6.0_23\bin>javac MyClass.java

 

D:\Program Files\Java\jdk1.6.0_23\bin>java MyClass

Shape

Shape

Circle

Shape

Triangle

 

 

Now Drawing Objects

 

Drawing Shape

Drawing Circle

Drawing Triangle