oops concept in Java

oops concept in Java

oops:

  To develop an application we use a programming language that follows one of the following concepts.

  1.procedure oriented concepts.
  2.object oriented concepts

1.procedure oriented concepts:

  The application that are developed using procedure oriented concepts are based on procedures or functions.

 Drabacks of procedure oriented concepts:

i.The application that are developed using procedure oriented concept or difficult to maintain and difficult to debug.
ii.The data in the applications that are developed using procedure oriented concepts is not secured.
iii.The data in the applications that are developed using procedure oriented concepts is open and it can be accessed by the entire applications,this mechanism is not suitable for developing distributed applications.
iv.In The procedured oriented languages lot of importance is given to the operations that perform on the data rather than to the data.

Note:The procedure oriented language are also called as "Structured programming language".

Ex:C,PASCAL,COBOL,FORTRAN Etc...

2.object oriented concepts:

 The application that are developed using object oriented concepts give lot of importance to the security ,they provide protection so that the data is not accessed by the unauthorised access.

Ex:C++,JAVA,.NET ETC...

-->Even though c++ is called as object oriented language,but according to the programming language experts it is called as partially object oriented language because of the following reasons.
i.An application in c++ can be developed without following the object oriented concepts.
ii.In c++ language Their is concept called friend functions using which we can access any data even though it is secured.

-->The object oriented concepts are derived from the real world,from the lifes of a human being so that the programming becomes simple.
-->The programmer can understand the concepts easily and implement them without facing any difficulty.
-->Using the object oriented concepts we can develop real time applications which are complex and large.Because the object oriented concepts are very strong.
-->The object oriented concepts has very strong fundamentalsentities called as 'class or 'object'.
-->A class is a specification of variables and methods .Where variables are used for storing the data and the methods are used for performing the operations.
-->A class is a collection of common features of a group of objects.
-->An object is any thing that exists physically in the real world.
-->A class doesnot exist physically but it is considered as a method or a blue print or a plan for creating the objects.we can create any number of objects for a class.with out a class we cannot create any object.
-->An object is considered as an imnstance of a class.

  The various object oriented concepts are.

  1.Encapsulations
  2.Abstraction
  3.Inheritance
  4.polymorphism


1.Encapsulations:

Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction.

Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding.

Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface.

The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
Example:

Let us look at an example that depicts encapsulation:

/* File name : EncapTest.java */
public class EncapTest{

   private String name;
   private String idNum;
   private int age;

   public int getAge(){
      return age;
   }

   public String getName(){
      return name;
   }

   public String getIdNum(){
      return idNum;
   }

   public void setAge( int newAge){
      age = newAge;
   }

   public void setName(String newName){
      name = newName;
   }

   public void setIdNum( String newId){
      idNum = newId;
   }
}

The public methods are the access points to this class' fields from the outside java world. Normally, these methods are referred as getters and setters. Therefore any class that wants to access the variables should access them through these getters and setters.

The variables of the EncapTest class can be access as below::

/* File name : RunEncap.java */
public class RunEncap{

   public static void main(String args[]){
      EncapTest encap = new EncapTest();
      encap.setName("James");
      encap.setAge(20);
      encap.setIdNum("12343ms");

      System.out.print("Name : " + encap.getName()+
                             " Age : "+ encap.getAge());
    }
}

This would produce the following result:

Name : James Age : 20

Benefits of Encapsulation:

i.The fields of a class can be made read-only or write-only.
ii.A class can have total control over what is stored in its fields.
iii.The users of a class do not know how the class stores its data. A class can change the data type of a field and users of the class do not need to change any of their code.

2.Abstraction

It is aprocess of hiding the unnessecessary information and presenting the required information.We can achive abstraction by using access specified using abstraction we can achive security.

Abstraction refers to the ability to make a class abstract in OOP. An abstract class is one that cannot be instantiated. All other functionality of the class still exists, and its fields, methods, and constructors are all accessed in the same manner. You just cannot create an instance of the abstract class.

If a class is abstract and cannot be instantiated, the class does not have much use unless it is subclass. This is typically how abstract classes come about during the design phase. A parent class contains the common functionality of a collection of child classes, but the parent class itself is too abstract to be used on its own.
Abstract Class:

Use the abstract keyword to declare a class abstract. The keyword appears in the class declaration somewhere before the class keyword.

/* File name : Employee.java */
public abstract class Employee
{
   private String name;
   private String address;
   private int number;
   public Employee(String name, String address, int number)
   {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }
   public double computePay()
   {
     System.out.println("Inside Employee computePay");
     return 0.0;
   }
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + this.name
       + " " + this.address);
   }
   public String toString()
   {
      return name + " " + address + " " + number;
   }
   public String getName()
   {
      return name;
   }
   public String getAddress()
   {
      return address;
   }
   public void setAddress(String newAddress)
   {
      address = newAddress;
   }
   public int getNumber()
   {
     return number;
   }
}

Notice that nothing is different in this Employee class. The class is now abstract, but it still has three fields, seven methods, and one constructor.

Now if you would try as follows:

/* File name : AbstractDemo.java */
public class AbstractDemo
{
   public static void main(String [] args)
   {
      /* Following is not allowed and would raise error */
      Employee e = new Employee("George W.", "Houston, TX", 43);

      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
    }
}

When you would compile above class then you would get the following error:

Employee.java:46: Employee is abstract; cannot be instantiated
      Employee e = new Employee("George W.", "Houston, TX", 43);
                   ^
1 error

Extending Abstract Class:

We can extend Employee class in normal way as follows:

/* File name : Salary.java */
public class Salary extends Employee
{
   private double salary; //Annual salary
   public Salary(String name, String address, int number, double
      salary)
   {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck()
   {
       System.out.println("Within mailCheck of Salary class ");
       System.out.println("Mailing check to " + getName()
       + " with salary " + salary);
   }
   public double getSalary()
   {
       return salary;
   }
   public void setSalary(double newSalary)
   {
       if(newSalary >= 0.0)
       {
          salary = newSalary;
       }
   }
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}

Here, we cannot instantiate a new Employee, but if we instantiate a new Salary object, the Salary object will inherit the three fields and seven methods from Employee.

/* File name : AbstractDemo.java */
public class AbstractDemo
{
   public static void main(String [] args)
   {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
      Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);

      System.out.println("Call mailCheck using Salary reference --");
      s.mailCheck();

      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
    }
}

This would produce the following result:

Constructing an Employee
Constructing an Employee
Call mailCheck using  Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.

Abstract Methods:

If you want a class to contain a particular method but you want the actual implementation of that method to be determined by child classes, you can declare the method in the parent class as abstract.

The abstract keyword is also used to declare a method as abstract. An abstract method consists of a method signature, but no method body.

Abstract method would have no definition, and its signature is followed by a semicolon, not curly braces as follows:

public abstract class Employee
{
   private String name;
   private String address;
   private int number;
  
   public abstract double computePay();
  
   //Remainder of class definition
}

Declaring a method as abstract has two results:

    The class must also be declared abstract. If a class contains an abstract method, the class must be abstract as well.

    Any child class must either override the abstract method or declare itself abstract.

A child class that inherits an abstract method must override it. If they do not, they must be abstract and any of their children must override it.

Eventually, a descendant class has to implement the abstract method; otherwise, you would have a hierarchy of abstract classes that cannot be instantiated.

If Salary is extending Employee class, then it is required to implement computePay() method as follows:

/* File name : Salary.java */
public class Salary extends Employee
{
   private double salary; // Annual salary
 
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }

   //Remainder of class definition
}

3.Inheritance:

  Inheritance can be defined as the process where one object acquires the properties of another. With the use of inheritance the information is made manageable in a hierarchical order.

When we talk about inheritance, the most commonly used keyword would be extends and implements. These words would determine whether one object IS-A type of another. By using these keywords we can make one object acquire the properties of another object.
IS-A Relationship:

IS-A is a way of saying : This object is a type of that object. Let us see how the extends keyword is used to achieve inheritance.

public class Animal{
}

public class Mammal extends Animal{
}

public class Reptile extends Animal{
}

public class Dog extends Mammal{
}

Now, based on the above example, In Object Oriented terms, the following are true:

    Animal is the superclass of Mammal class.

    Animal is the superclass of Reptile class.

    Mammal and Reptile are subclasses of Animal class.

    Dog is the subclass of both Mammal and Animal classes.

Now, if we consider the IS-A relationship, we can say:

    Mammal IS-A Animal

    Reptile IS-A Animal

    Dog IS-A Mammal

    Hence : Dog IS-A Animal as well

With use of the extends keyword the subclasses will be able to inherit all the properties of the superclass except for the private properties of the superclass.

We can assure that Mammal is actually an Animal with the use of the instance operator.
Example:

public class Dog extends Mammal{

   public static void main(String args[]){

      Animal a = new Animal();
      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
}

This would produce the following result:

true
true
true

Since we have a good understanding of the extends keyword let us look into how the implements keyword is used to get the IS-A relationship.

The implements keyword is used by classes by inherit from interfaces. Interfaces can never be extended by the classes.
Example:

public interface Animal {}

public class Mammal implements Animal{
}

public class Dog extends Mammal{
}

The instanceof Keyword:

Let us use the instanceof operator to check determine whether Mammal is actually an Animal, and dog is actually an Animal

interface Animal{}

class Mammal implements Animal{}

public class Dog extends Mammal{
   public static void main(String args[]){

      Mammal m = new Mammal();
      Dog d = new Dog();

      System.out.println(m instanceof Animal);
      System.out.println(d instanceof Mammal);
      System.out.println(d instanceof Animal);
   }
}

This would produce the following result:

true
true
true

HAS-A relationship:

These relationships are mainly based on the usage. This determines whether a certain class HAS-A certain thing. This relationship helps to reduce duplication of code as well as bugs.

Lets us look into an example:

public class Vehicle{}
public class Speed{}
public class Van extends Vehicle{
    private Speed sp;
}

This shows that class Van HAS-A Speed. By having a separate class for Speed, we do not have to put the entire code that belongs to speed inside the Van class., which makes it possible to reuse the Speed class in multiple applications.

In Object-Oriented feature, the users do not need to bother about which object is doing the real work. To achieve this, the Van class hides the implementation details from the users of the Van class. So basically what happens is the users would ask the Van class to do a certain action and the Van class will either do the work by itself or ask another class to perform the action.

A very important fact to remember is that Java only supports only single inheritance. This means that a class cannot extend more than one class. Therefore following is illegal:

public class extends Animal, Mammal{}

However, a class can implement one or more interfaces. This has made Java get rid of the impossibility of multiple inheritance.

4.Polymorphism

  Polymorphism is the ability of an object to take on many forms. The most common use of polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.

Any Java object that can pass more than one IS-A test is considered to be polymorphic. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.

It is important to know that the only possible way to access an object is through a reference variable. A reference variable can be of only one type. Once declared, the type of a reference variable cannot be changed.

The reference variable can be reassigned to other objects provided that it is not declared final. The type of the reference variable would determine the methods that it can invoke on the object.

A reference variable can refer to any object of its declared type or any subtype of its declared type. A reference variable can be declared as a class or interface type.
Example:

Let us look at an example.

public interface Vegetarian{}
public class Animal{}
public class Deer extends Animal implements Vegetarian{}

Now, the Deer class is considered to be polymorphic since this has multiple inheritance. Following are true for the above example:

    A Deer IS-A Animal

    A Deer IS-A Vegetarian

    A Deer IS-A Deer

    A Deer IS-A Object

When we apply the reference variable facts to a Deer object reference, the following declarations are legal:

Deer d = new Deer();
Animal a = d;
Vegetarian v = d;
Object o = d;

All the reference variables d,a,v,o refer to the same Deer object in the heap.
Virtual Methods:

In this section, I will show you how the behavior of overridden methods in Java allows you to take advantage of polymorphism when designing your classes.

We already have discussed method overriding, where a child class can override a method in its parent. An overridden method is essentially hidden in the parent class, and is not invoked unless the child class uses the super keyword within the overriding method.

/* File name : Employee.java */
public class Employee
{
   private String name;
   private String address;
   private int number;
   public Employee(String name, String address, int number)
   {
      System.out.println("Constructing an Employee");
      this.name = name;
      this.address = address;
      this.number = number;
   }
   public void mailCheck()
   {
      System.out.println("Mailing a check to " + this.name
       + " " + this.address);
   }
   public String toString()
   {
      return name + " " + address + " " + number;
   }
   public String getName()
   {
      return name;
   }
   public String getAddress()
   {
      return address;
   }
   public void setAddress(String newAddress)
   {
      address = newAddress;
   }
   public int getNumber()
   {
     return number;
   }
}

Now suppose we extend Employee class as follows:

/* File name : Salary.java */
public class Salary extends Employee
{
   private double salary; //Annual salary
   public Salary(String name, String address, int number, double
      salary)
   {
       super(name, address, number);
       setSalary(salary);
   }
   public void mailCheck()
   {
       System.out.println("Within mailCheck of Salary class ");
       System.out.println("Mailing check to " + getName()
       + " with salary " + salary);
   }
   public double getSalary()
   {
       return salary;
   }
   public void setSalary(double newSalary)
   {
       if(newSalary >= 0.0)
       {
          salary = newSalary;
       }
   }
   public double computePay()
   {
      System.out.println("Computing salary pay for " + getName());
      return salary/52;
   }
}

Now, you study the following program carefully and try to determine its output:

/* File name : VirtualDemo.java */
public class VirtualDemo
{
   public static void main(String [] args)
   {
      Salary s = new Salary("Mohd Mohtashim", "Ambehta, UP", 3, 3600.00);
      Employee e = new Salary("John Adams", "Boston, MA", 2, 2400.00);
      System.out.println("Call mailCheck using Salary reference --");
      s.mailCheck();
      System.out.println("\n Call mailCheck using Employee reference--");
      e.mailCheck();
    }
}

This would produce the following result:

Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to Mohd Mohtashim with salary 3600.0

Call mailCheck using Employee reference--
Within mailCheck of Salary class
Mailing check to John Adams with salary 2400.0

Here, we instantiate two Salary objects . one using a Salary reference s, and the other using an Employee reference e.

While invoking s.mailCheck() the compiler sees mailCheck() in the Salary class at compile time, and the JVM invokes mailCheck() in the Salary class at run time.

Invoking mailCheck() on e is quite different because e is an Employee reference. When the compiler sees e.mailCheck(), the compiler sees the mailCheck() method in the Employee class.

Here, at compile time, the compiler used mailCheck() in Employee to validate this statement. At run time, however, the JVM invokes mailCheck() in the Salary class.

This behavior is referred to as virtual method invocation, and the methods are referred to as virtual methods. All methods in Java behave in this manner, whereby an overridden method is invoked at run time, no matter what data type the reference is that was used in the source code at compile time.

0 comments:

Post a Comment