Back to top

#1 Object Oriented Programming

Posted on: 06/24/2012, 10:36 PM

It is often said Object Oriented Programming(OOP) is based on how the real world works. That is true in the sense that, it assumes objects and how they relate to each other in the program. In OOP there is something called a Class. A is a package for the variables and methods, which are called 'Members of the Class'. Now a Class is used as a blueprint for the Object.

For example, consider a blueprint of a house. Now the blueprint is used to make n number of houses. These houses will be the same in every aspect of detail because their blueprint is the same. Same goes with the Classes and Objects. Every Object created is the same in terms of what it contains,i.e. it is a working copy of the Class. But the details of the members it contains can be different for every object. Like in the above example, the sink in the kitchen exists for all, but the design can be changed to the wish of the owner.

Now, one would ask what about the security of the data stored inside the objects. The answer is Encapsulation. This is one of the principles of OOP. It is the ability to bundle code and data together in one place and hide it from being accessed from the outside world. To access it, one has to go through the associated code. Let us consider a class Student. Every student will have common attributes like Name, Age, Sex. Say we have three students, to know their name we can use a getName() method. This function is the associated code to the data. Since the encapsulation prevents one to read the data directly from the memory, we would have to use functions to get it.

The member functions can also only be accessed by Objects of the same Class, and Objects of Class who have inherited the it. This principle of Inheritance is one of the most powerful in OOP. Consider a Class Shape. There are two kinds of shapes, 2D and 3D. Now again coming to the fact that, OOP works like real world objects. This will exactly demonstrate that. Now we make a class for 2D and 3D. These two classes will inherit the Class Shape which includes the getSize() function (which is either area/volume depending on the type of shape).

The 2D and 3D Classes contain their own individual properties as well as the properties of the Class shape. Now, we declare Class Circle, Cube, Rectangle, these three inherit 2D/3D whichever corresponds to their type of shape. The three Classes we declared will in turn have their own unique properties. The Object of these three classes will be able to use the members of all the Classes in its line of inheritance (it can be restricted by setting access specifiers). This basically saves a lot of coding space. Imagine creating variables for each one of them instead of just inheriting it and reusing it. Re-usability is the biggest advantage of inheritance.


#2 Classes and Interface

Posted on: 07/20/2012, 10:00 PM

A class is basically a package for the variables and methods often called 'Members of the Class'. Every method heading in a class has to be defined (i.e. it should have its own body definition). These variables, methods can be used by an instance of the class, Object. When a class is inherited by a derived class, its methods/variables can be accessed by the instance of the derived class as well (depending on the access modifiers).

A lot of times while making an application one would encounter the concept of overloading/over-riding methods. At times there would be situations where you would not use the method definition of the base class but would want a different method definition in the derived class.

Hierarchy of Shape Classes

Consider a program to calculate the size (area/volume) of shapes. Lets take 3 different shapes Cube, Sphere, Circle. Now these three are shapes but of different kind. Cube, Sphere are 3D Shapes and Circle is a 2D Shape. The Common thing among the three is that all three are Shapes, but then not Every Shape is 2D/3D, it can either be one of them.

Now if we try to create a class Shape for all the three selections we have, it would be really messy and would defeat the whole purpose of using an object oriented approach. That would mean, having all the data in a single object, even though we would need the data for only one of the selections which is either circle/cube/sphere

We can use the concept of inheritance to have a more efficient piece of code. Now if we have a class Shape with attributes which are common to our selections and then extend the Shape class to classes of our selections that would solve our problem of having the data of all the selections in a single object.

The method getSize() is a common method we can use for the three selections. There would be an issue here though, we cannot have the same method definition for the three selections. Well then this would mean, we would have to make the getSize() method definitions in the respective classes. Also what the getSize() actually does is get the Area(for circle) and Volume/Surface Area(for cube, sphere). But the whole point of the Base class shape is to have its properties copied into its derived class, and since we aren't really specifying anything it the Shape class what use will it be? So, if the base classes are to be of any use here, it could only be possible if they enforce the properties on its derived classes. We know that there is no such way to do so using a Concrete Base Class.

This is where an Abstract Class can be used. Unlike a concrete class where every method has to have a method definition, abstract classes can have abstract methods. Abstract methods are methods with only headings and no body. They end with a semicolon instead of a method definition. Also the keyword abstract has to be added. Example, public abstract int abstractMethod();
So basically an abstract class can contain two types of methods: -Abstract Methods (Without method definition) -Non-Abstract Methods (With method definition)

Any class which contains even a single abstract method, has to be a abstract class. To make a class abstract, keyword abstract has to be used.
When a derived class extends an abstract class, it has to define each and every abstract method from the abstract class. If at all it does not define an abstract method and wants to keep it that way, then the class has to become abstract. I will show this when I talk about the above discussed program with abstract classes as base class and not concrete class as a base class. An abstract method can also never be private.

So now if we make Shape an abstract class, the getSize() method would become abstract as well without any body definition. When the classes ThreeDShape and TwoDShape extent Shape, the method getSize() would be enforced onto them. Now either they would give a definition to getSize() or they would make it abstract, which means the class itself would have to become an abstract class.

public abstract class Shape {
    public abstract double getSize();
  
    @Override
    public String toString()
    {
        return " of type " + this.getClass();
    } // toString
}

            

As I mentioned before getSize() returns area/volume depending on the type of shape it is. So ThreeDShape and TwoDShape would define it to return volume and area respectively. Any shape which extends ThreeDShape and TwoDShape would have Volume/Area, so we can declare getVolume() and getArea() as abstract methods in the respective classes. Also we would add one more abstract method getSurfaceArea() to ThreeDShape.

public abstract class ThreeDShape extends Shape{
    public double getSize()
    {
        return getVolume();
     } // getSize

    public abstract double getVolume();
    public abstract double getSurfaceArea();

     public String toString()
    {
        return "This 3D Shape is of type " + this.getClass();
     } // toString
}

public abstract class TwoDShape extends Shape{
    public double getSize()
     {
        return getArea();
      } // getSize

    public abstract double getArea();

    @Override
    public String toString()
     {
        return "This 2D Shape is of " + this.getClass();
      } // toString
}

            

Whichever class the selective shapes we make, extends, they will have to provide method definitions for all the abstract methods in the hierarchy of inheritance. They can of course add their own methods with definitions. Example, in the Circle Class we would add the variable Radius of type double and its get/set methods.

public class Circle extends TwoDShape {
    private double Radius;

   public Circle()
     {
        setRadius();
      } // constructor

   public double getRadius()
     {
        return Radius;
      } // get Radius

    public String setRadius()
     {
        Scanner input=new scanner(System.in);
        System.out.println("Enter the radius for circle: ");
        Radius = Double.parseDouble(input.next());
        return "";
      } // setRadius
      
    @Override
    public double getArea() 
      {
       return Math.PI * (getRadius() * getRadius());
       }

     @Override
    public String toString()
       {
        return (super.toString()+"\n"+"This circle has a 
                radius of " + getRadius() + "\nand Area of:" 
                                                + getArea());
        } // toString
           }

public class Cube extends ThreeDShape {
  Double Side;

  Cube()
      {
        setSide();
      }
   public String setSide()
      {
        Scanner input=new scanner(System.in); 
        System.out.println("Enter the side for cube: ");
        Side = Double.parseDouble(input.next());
        return " ";
       }

   public double getSide()
       {
             return Side;
        }

    public double getVolume()
      {
         return getSide()*getSide()*getSide();
      } //

    public double getSurfaceArea()
    {
        return 6*getSide()*getSide();
    }

    @Override
    public String toString()
    {
        return super.toString()
            + "\n The Side of Cube is:" +getSide()
            + "\n The Volume of Cube is:" +getVolume()
            + "\n The Surface Area of Cube is:" +getSurfaceArea();
    } //
}


public class Sphere extends ThreeDShape{
   double Radius;

    Sphere()
    {
     setRadius();
    }

    public void setRadius()
    {
        Scanner input=new scanner(System.in);            
        System.out.println("Enter the radius for sphere: ");
        Radius = Double.parseDouble(input.next());
    }

    public double getRadius()
    {
        return Radius;
    }
    
    @Override
    public double getVolume() 
    {
        return (4/3)*Math.PI*getRadius()*getRadius()*getRadius();
    }

    @Override
    public double getSurfaceArea() 
    {
        return 4*Math.PI*getRadius()*getRadius();
    }

    public String toString()
    {
        return super.toString()
               + " \n The Radius of the Sphere is:" + getRadius()
               + " \n The Volume of the Sphere is:" + getVolume()
               + " \n The Surface Area of the Sphere is:" 
               + getSurfaceArea();
    }
}

            

Abstract classes are usually at the top of the hierarchy. It is always good practice to have an abstract class as the base class. You will encounter a lot of code with such practices, because it makes sense! Note: Abstract classes cannot have their own instances. But they can be used as a type to contain the objects of its derived classes(Upcasting). It is also legal to only declare a class variable of an abstract class without instantiating an object.

Well now that you know what the main purpose of an abstract class is (to enforce certain methods in the inheritance hierarchy), a question pops up about have more than one base class. Java does not allow a derived class to have multiple base classes like C++ does. This is definitely a drawback from the perspective of inheritance.

There is a way around it though, an interface. An interface, in a way, is the extreme version of abstract classes. It acts as a contract, just like an abstract class. It is not a class though, it is a type on its own. Any concrete/abstract class would use the keyword implements and not extends to inherit the interface. Example, -public class MyClass implements interface1{} -public abstract class MyClass implements interface1{}

An interface can contain variables and methods both.

The methods would be absolutely the same as an abstract method but without the keyword abstract. The rules are the same as any abstract class when it comes to inheritance. Every method has to be given a definition. The methods in an interface are always public. They cannot be private, protected or package access. Any method not defined by the class that implements an interface has to declare the method as an abstract, which makes the inheriting class abstract as well.

One would wonder how we pass and use a parameter in the methods, since we cannot create an instance(object) of an interface. Since interface is a type, this allows us to write a method with a parameter of an interface type and that parameter will accept as an argument any class we later use to implement the interface.

Only constants can be declared in an interface. The variables in an interface are assumed to be public, static and final. So it does not matter if the syntax isn't applied, the variables can be declared just like a variable without any modifier restriction. Sometimes java users use interfaces to take care of number of miscellaneous details that do not really fit the spirit of an interface. Example, to use it as a way to name a group of defined constants. So a class that implements that interface would automatically be able to use those constants.

Could an interface inherit another interface? Yes. When an interface inherits another interface, it does not 'implement' but it 'extends' its. Everything else is the same. As in, the number of interfaces an interface can extend is not limited. So don't let the syntax fool you into thinking that an interface 'extend' only one interface just like a class can 'extend' only one class.

The reason java allows having only one base class for a derived class, is because if there were two base classes, the two base classes could provide different and inconsistent definitions of a single method heading. But with interfaces such a problem of bad method headings cannot arise. However, that does not mean there is no flaw in having interfaces as well. There are situations where an interface can be inconsistent as well.

Consider two interfaces Interface1, Interface2. Both contain a constant int num; Interface1 -> int num=0; Interface2 -> int num=42; This is clearly illegal if a class implements both these interfaces. Because the class would end up having a constant num with values 0 and 42 at the same time.

A similar situation could arise with methods. Consider Interface1, Interface2 having a method with the same name but different return types. Interface1 -> public int getStuff(); Interface2 -> public String getStuff(); This is clearly illegal if a class implements both these interfaces. Because the class would end up having a method getStuff() that returns int and String at the same time. Note: We cannot overload getStuff() based on the type returned; so, overloading cannot be used to get around this problem.

P.S: Abstract Methods and Interfaces do not have semantics since there is no method definition. Make sure you mention the semantics in the Javadoc comments. It is the responsibility of the programmer to apply them. Because the interface/abstract methods assume the semantics are being satisfied. If not satisfied the class may not behave the way it is supposed to.