OOP concepts




Before talking about some lessons ( Var-Agrs, Enums...etc ), I think it is better to talk about Object Oriented Programming ( OOP )  in Java. This part is the core of Java or any other object oriented programming language. In this section we talk about three things.
  1. Encapsulation
  2. Inheritance
  3. Polymorphism

Encapsulation



Encapsulation is like this. Protected data can be seen using this concept.
Encapsulation is the technique of binding data and its corresponding methods into a single unit. This is the combination of data hiding and abstraction. 

  • This can be seen as protecting data in programming.
  • When you declared a field with private access, it can't be accessed anyone from outside of the class. Encapsulation provide a access to these private fields via public methods.
  • This can be declared as a protective gate.
  • get and set methods are used to access the protected fields. 

Following example will describe about encapsulation.

public class Student {
 
   private int id;
   private String name;
 
   public String getName() {
      return name;
   }
   public void setName(String name) {
      this.name = name;
   }
   public int getId() {
      return id;
   }
   public void setId(int id) {
      this.id = id;
   }
}

public class Test{
 
   public static void main(String args[]){
  
      Student obj = new Student();
      obj.setId(1);
      obj.setName("John");
  
      System.out.println("ID : " + obj.getId());
      System.out.println("Name : " + obj.getName());
   }
}


  • In this example you can see there are two classes called Student and Test.
  • You can see two variables called name and id with private access modifier. It means these variables are visible only with in the class.
  • But in this program we have used them in another class called Test  and we have accessed it.
  • It is done by get( ) and set( ) methods. set method is used to set the value and get method is used to call the value.
  • In set method it is used a keyword called 'this'. It is used to say "private String name" is equal to "public void setname (String name)".

Advantages of Encapsulation.

  • Encapsulated code is more flexible, maintainable and extensible.
  • The field of a class can be made read only or write only.
  • Allows admin to control who can access what.
  • It allows to change one part of the code without having any effects to the other parts. 
CLICK HERE to download a program with encapsulation and user inputs.



Inheritance 




Try it yourself. If you can also your father can do it definitely. 
  • This concept can be seen in real world. It is like the relationship between parents and children. 
  • Inheritance allows us to create the bond between super classes (parents) and subclasses (children).
  • We can inherit from class of interface. If inherit from class, we use extends keyword and if it is a interface, we use implements keyword.

Inheritance in classes

  • This can be understood using following example. 
  • There are four cars in  below picture. 
  • These are types of cars.
  • You can create a super class called "Car" and then you can create other sub-classes "Micro_car", "Hatchback" and "Sedan".
  • These sub classes are inherited by Car class.

class Car{  }

class Micro_car extends Car { }
class Hatchback extends Car { }
class Sedan extends Car { }



Inheritance in interfaces

  • We talk more about this thing in later posts. But now I will give simple example to understand about inheritance in interfaces.
  • We use implements keyword to do this.

public interface DriveCar{
   void accelerate( );
   void stop( );
}

public class Car implements DriveCar{
   void accelerate( ) { /*implementations*/ }
   oid stop( ) { /*implementations*/ }
}


IS-A relationship

  • IS-A refers inheritance or implementation.
  • Lets get a real life example.


  • Mitsubishi Pajero 2014 is a latest SUV product of Mitsubishi motors.
  • It is SUV range vehicle. 
  • There are 4 types in 2014 model.
    1. GLX
    2. GLX-R
    3. VRX
    4. EXCEED

  • Now you can say GLX is a type of Mitsubishi Pajero.
  • Now you can say GLX-R is a type of Mitsubishi Pajero.
  • Now you can say VRX is a type of Mitsubishi Pajero.
  • Now you can say EXCEED is a type of Mitsubishi Pajero.
 Then again you can say,
  • Mitsubishi Pajero is a SUV.
It means SUV is a super parent then Pajero is a parent when other four types are children.



If you want to create a classes for this example, it can be done like this.

public class Suv {  }
public class Mitsubishi_Pajero extends Suv {  }
public class Glx extends Mitsubishi_Pajero {  } 
public class Glx_R extends Mitsubishi_Pajero {  }
public class Vrx extends Mitsubishi_Pajero {  }
public class Exceed extends Mitsubishi_Pajero {  }


Generalization


Generalization is the process of casting sub classes into super classes. Think about above example.




Specialization


This is the up side down process of generalization. Look at this figure. 




Has-A Relationship 

  • Has-A relationship can be understood as a type of inheritance and this is also known as Composition and Aggregation.
  • it means an instance of one class has a reference to another instance of another class or same class.
  • Lets get a real life example.
Car IS-A vehicle and it HAS-A Engine.

class Vehicle {  }
   class Car{
       Engine obj = new Engine(); 
   }
   class Engine {  }


Aggregation

  • This means a directional association between objects.
  • When an object has another object, we can define a direction between then to specify which object contains another object.
  • This method is useful for code re-usability. 
Ex: Car has Air bags.
      But a car can exist without airbags.


Composition

  • A restricted aggregation is called composition.
  • It means objects are associated strongly.
  • There is a composition when an object( first object ) contains another object and that contained object can't exist without first object.
EX: Class contain students.
      A student cannot exist without a class.

Why use Inheritance ?

  • Promote code reuse
  • To use with Polymorphism 


Polymorphism






Now you may think what is he gonna do now with these type of pictures. You know that this is Vanessa Hudgens dressed with different costumes. She looks different with different  costumes. It means same person with different kits.

  • Polymorphism also means many forms of a one object.
  • When programming you may have to use same method in several times in different classes with different parameters. 
  • But you can think it cannot be done, because we have used that method at a one time.
  • But it is not real with OOP, Java allows you to create same method in several times in different classes with different parameters. 
  • Method name is like Vanessa Hudgens. But her costumes can be changed. ( inner and outer).
  • I have mentioned that polymorphism is a theory  that is giving you to use same methods again and again.
  • This can be done in two ways.
    1. Method overriding
    2. Method overloading

    Reference variables

    Before talking about these two things, it is necessary to talk about Reference variable. You need to understand this theory before talking about overloading or overriding. A variable that refers the class name is known as reference variable. Reference variable is the only way to access objects.You may remember how to create an objects.
                  
                      Apple obj = new Apple( );

    You can divide that statement into two steps.

                                        Apple obj;
                      obj = new Apple( );

    The first line shows you how to create Apple type reference variable. Then the reference variable is converted into an object. 


    Apple( ) is a constructor(You will be learnt about constructors later). Generally it does not return anything. But you can see we don't use void keyword. Thing is this, really a constructor return something called "class object" (object of the class). It has not a name. So it is called "Anonymous object". Then this anonymous object is assigned to reference variable(obj). 





    There are some rules to define reference variables.
    • A reference variable can be only one type and it can be declared once. That type never changed.
    • A reference variable can refer to a sub-type object same type or a super type of the object.
    • A reference variable type determine which methods can be called.

    • You can see, when creating objects left side define as a reference type (class type/super type) and right side define as a object type.
    • When method calling it should be considered about object type.
    • When instance variable access then consider about reference type.
    • Object type determines which overridden method is used at run-time.
    • Reference type determine which overloaded method will be used at compile time.

    Reference variable casting

    There are two types of casting.
    1. Upward casting
    2. Downward casting

    Upward casting (Automatic type conversions)

    Following example demonstrate how to do upward casting in Java.


    class Fruit { }
    
    class Mango extends Fruit { }
    
    public class Apple {
       public static void main(String args[]) {
          Mango mango = new Mango();
          Fruit fruit = mango; // upcast with no explicit cast
          Fruit fruit2 = (Fruit) mango; // upcast with explicit cast
       }
    }
    
    


    This conversion can be done only if the following conditions are true.
    • Two types should be compatible (int/float, int/long).
    • Destination type should be larger than the source type.

    Downward casting (Explicit type conversions)


      


    This type of conversions is useful if you want to create conversion between incompatible types. What is to be done if you want to convert long value to byte value ? We have talked about data type casting in Data types in Java post. In this section we are gonna talk about object casting. This is not like upward casting. You should specify the target type.

    In above example you will be able to see a ClassCastException exception when you run the program.

    Method overriding

    • In this type you can redefine method with limited scope.
    • It means when you override a method, method name, arguments and return type should be same as overridden method.  
    • final, static and private methods cannot be overridden.
    • Only inherited method may be overridden.
    • Overriding method cannot be less public than overridden method.
    You can try this example to understand about method overriding.


    class Apple {
       void eat() {
          System.out.println("Apple");
       }
    }
    
    class RedApple extends Apple {
       void eat() {
          System.out.println("Red Apple");
       }
    }
    
    public class Fruits {
       public static void main(String args[]) {
    
          Apple apple = new Apple();
          Apple apple2 = new RedApple();
    
          apple.eat();
          apple2.eat();
       }
    }
    

    Method overloading 

    • This is little bit different with overriding. 
    • Overloaded methods have the same name and must have different argument list. Argument may differ in data type or number or both.
    • The return type of the overloaded methods can be different or same. If argument list is different, return types are also different. 
    • They may have different access modifiers.
    • May throw different exceptions( Later on we talk about Exceptions ).

    class Processor{
       void showType(){
            System.out.println("Intel and AMD are the popular.");
       }
    }
    
    class Intel extends Processor{
       void showType(){
            System.out.println("Intel is leading vendor.");
       }
       void showType(String gen){
            System.out.println("Intel has " + gen + " generations.");
       }
    }
    
    public class MotherBoard{
       public static void main(String args[]){
          Processor obj1 = new Processor();
          Processor obj2 = new Intel();
          Intel obj3 = new Intel();
    
          obj1.showType();
          obj2.showType();
          obj3.showType("four");
       }
    }
    
    






    OOP concepts OOP concepts Reviewed by Ravi Yasas on 12:07 AM Rating: 5

    1 comment:

    1. It's very impressive if you wrote all this by yourself! Great idea about pictures! It's fun and also good for memorization.
      I've found it useful, also I like laconic-way of explanation. But examples, need them!
      Also, as for me, it's better to separate one big article to more, each topic in it's own place, you know.

      I want to tell you something. Mediafire has annoying ads. In my opinion it's much better to use pastebin.com or something that made especially for code sharing.
      Here, my example of Encapsulation, how we can use it in practice: http://pastebin.com/LabrkGt5
      Let me know what do you think.

      ReplyDelete

    Powered by Blogger.