Showing posts with label Java Basic. Show all posts
Showing posts with label Java Basic. Show all posts

Friday, 27 March 2015

Method Overriding in Java

Method Overriding in Java

If subclass (child class) has the same method as declared in the parent class, it is known as method overriding in java.
In other words, If subclass provides the specific implementation of the method that has been provided by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

  • Method overriding is used to provide specific implementation of a method that is already provided by its super class.
  • Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

  1. method must have same name as in the parent class
  2. method must have same parameter as in the parent class.
  3. must be IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method overriding.
  1. class Vehicle{  
  2.   void run(){System.out.println("Vehicle is running");}  
  3. }  
  4. class Bike extends Vehicle{  
  5.     
  6.   public static void main(String args[]){  
  7.   Bike obj = new Bike();  
  8.   obj.run();  
  9.   }  
  10. }  
Output:Vehicle is running
Problem is that I have to provide a specific implementation of run() method in subclass that is why we use method overriding.

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class but it has some specific implementation. The name and parameter of the method is same and there is IS-A relationship between the classes, so there is method overriding.
  1. class Vehicle{  
  2. void run(){System.out.println("Vehicle is running");}  
  3. }  
  4. class Bike2 extends Vehicle{  
  5. void run(){System.out.println("Bike is running safely");}  
  6.   
  7. public static void main(String args[]){  
  8. Bike2 obj = new Bike2();  
  9. obj.run();  
  10. }  
Output:Bike is running safely

Real example of Java Method Overriding

Consider a scenario, Bank is a class that provides functionality to get rate of interest. But, rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could provide 8%, 7% and 9% rate of interest.


  1. class Bank{  
  2. int getRateOfInterest(){return 0;}  
  3. }  
  4.   
  5. class SBI extends Bank{  
  6. int getRateOfInterest(){return 8;}  
  7. }  
  8.   
  9. class ICICI extends Bank{  
  10. int getRateOfInterest(){return 7;}  
  11. }  
  12. class AXIS extends Bank{  
  13. int getRateOfInterest(){return 9;}  
  14. }  
  15.   
  16. class Test2{  
  17. public static void main(String args[]){  
  18. SBI s=new SBI();  
  19. ICICI i=new ICICI();  
  20. AXIS a=new AXIS();  
  21. System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());  
  22. System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());  
  23. System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());  
  24. }  
  25. }  
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

Can we override static method?

No, static method cannot be overridden. It can be proved by runtime polymorphism, so we will learn it later.

Why we cannot override static method?

because static method is bound with class whereas instance method is bound with object. Static belongs to class area and instance belongs to heap area.

Can we override java main method?

No, because main is a static method.

Aggregation in Java

Aggregation in Java

If a class have an entity reference, it is known as Aggregation. Aggregation represents HAS-A relationship.
Consider a situation, Employee object contains many informations such as id, name, emailId etc. It contains one more object named address, which contains its own informations such as city, state, country, zipcode etc. as given below.
  1. class Employee{  
  2. int id;  
  3. String name;  
  4. Address address;//Address is a class  
  5. ...  
  6. }  
In such case, Employee has an entity reference address, so relationship is Employee HAS-A address.

Why use Aggregation?

  • For Code Reusability.

Simple Example of Aggregation

aggregation example
In this example, we have created the reference of Operation class in the Circle class.
  1. class Operation{  
  2.  int square(int n){  
  3.   return n*n;  
  4.  }  
  5. }  
  6.   
  7. class Circle{  
  8.  Operation op;//aggregation  
  9.  double pi=3.14;  
  10.     
  11.  double area(int radius){  
  12.    op=new Operation();  
  13.    int rsquare=op.square(radius);//code reusability (i.e. delegates the method call).  
  14.    return pi*rsquare;  
  15.  }  
  16.   
  17.      
  18.     
  19.  public static void main(String args[]){  
  20.    Circle c=new Circle();  
  21.    double result=c.area(5);  
  22.    System.out.println(result);  
  23.  }  
  24. }  
Output:78.5
      

When use Aggregation?

  • Code reuse is also best achieved by aggregation when there is no is-a relationship.
  • Inheritance should be used only if the relationship is-a is maintained throughout the lifetime of the objects involved; otherwise, aggregation is the best choice.

Understanding meaningful example of Aggregation

In this example, Employee has an object of Address, address object contains its own informations such as city, state, country etc. In such case relationship is Employee HAS-A address.

Address.java

  1. public class Address {  
  2. String city,state,country;  
  3.   
  4. public Address(String city, String state, String country) {  
  5.     this.city = city;  
  6.     this.state = state;  
  7.     this.country = country;  
  8. }  
  9.   
  10. }  

Emp.java

  1. public class Emp {  
  2. int id;  
  3. String name;  
  4. Address address;  
  5.   
  6. public Emp(int id, String name,Address address) {  
  7.     this.id = id;  
  8.     this.name = name;  
  9.     this.address=address;  
  10. }  
  11.   
  12. void display(){  
  13. System.out.println(id+" "+name);  
  14. System.out.println(address.city+" "+address.state+" "+address.country);  
  15. }  
  16.   
  17. public static void main(String[] args) {  
  18. Address address1=new Address("gzb","UP","india");  
  19. Address address2=new Address("gno","UP","india");  
  20.   
  21. Emp e=new Emp(111,"varun",address1);  
  22. Emp e2=new Emp(112,"arun",address2);  
  23.       
  24. e.display();  
  25. e2.display();  
  26.       
  27. }  
  28. }  
Output:111 varun
       gzb UP india
       112 arun
       gno UP india     

Inheritance in Java

Inheritance in Java

Inheritance in java is a mechanism in which one object acquires all the properties and behaviors of parent object.
The idea behind inheritance in java is that you can create new classes that are built upon existing classes. When you inherit from an existing class, you can reuse methods and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship.

Why use inheritance in java

  • For Method Overriding (so runtime polymorphism can be achieved).
  • For Code Reusability.

Syntax of Java Inheritance

  1. class Subclass-name extends Superclass-name  
  2. {  
  3.    //methods and fields  
  4. }  
The extends keyword indicates that you are making a new class that derives from an existing class.
In the terminology of Java, a class that is inherited is called a super class. The new class is called a subclass.

Understanding the simple example of inheritance

inheritance in java
As displayed in the above figure, Programmer is the subclass and Employee is the superclass. Relationship between two classes is Programmer IS-A Employee.It means that Programmer is a type of Employee.
  1. class Employee{  
  2.  float salary=40000;  
  3. }  
  4. class Programmer extends Employee{  
  5.  int bonus=10000;  
  6.  public static void main(String args[]){  
  7.    Programmer p=new Programmer();  
  8.    System.out.println("Programmer salary is:"+p.salary);  
  9.    System.out.println("Bonus of Programmer is:"+p.bonus);  
  10. }  
  11. }  

 Programmer salary is:40000.0
 Bonus of programmer is:10000
In the above example, Programmer object can access the field of own class as well as of Employee class i.e. code reusability.


Types of inheritance in java

On the basis of class, there can be three types of inheritance in java: single, multilevel and hierarchical.
In java programming, multiple and hybrid inheritance is supported through interface only. We will learn about interfaces later.
types of inheritance in java

Note: Multiple inheritance is not supported in java through class.

When a class extends multiple classes i.e. known as multiple inheritance. For Example:
multiple inheritance in java


Q) Why multiple inheritance is not supported in java?

To reduce the complexity and simplify the language, multiple inheritance is not supported in java.
Consider a scenario where A, B and C are three classes. The C class inherits A and B classes. If A and B classes have same method and you call it from child class object, there will be ambiguity to call method of A or B class.
Since compile time errors are better than runtime errors, java renders compile time error if you inherit 2 classes. So whether you have same method or different, there will be compile time error now.
  1. class A{  
  2. void msg(){System.out.println("Hello");}  
  3. }  
  4. class B{  
  5. void msg(){System.out.println("Welcome");}  
  6. }  
  7. class C extends A,B{//suppose if it were  
  8.    
  9.  Public Static void main(String args[]){  
  10.    C obj=new C();  
  11.    obj.msg();//Now which msg() method would be invoked?  
  12. }  
  13. }  

 Compile Time Error