Chapter 5
Chapter 5
For method overloading, we provide several different method definition in the class with the same
name but different parameter list.
You can overload a method as long as the parameter lists are distinct enough for the complier to
able to distinguish which method you want to invoke. Certainly if the number of parameters is
different, the overloading is valid as shown in the following two Method Signatures (Method Header
without Definition)
public double volume(double l, double w, double h );//three Parameters
Changing the order of parameter list is just like changing the parameter list example of valid
overloading
classOverload
{
void demo (int a)
{
System.out.println ("a: " + a);
}
void demo (int a, int b)
{
System.out.println ("a and b: " + a + "," + b);
}
double demo(double a) {
System.out.println("double a: " + a);
return a*a;
}
}
classMethodOverloading
{
publicstaticvoid main (Stringargs [])
{
OverloadObj = newOverload();
double result;
Obj .demo(10);
Obj .demo(10, 20);
result = Obj .demo(5.5);
System.out.println("O/P : " + result);
}
}
2) Method Overriding
Child class has the same method as of base class. In such cases child class overrides
the parent class method without even touching the source code of the base class. This
feature is known as method overriding.
classVehicle{
publicvoid move (){
System.out.println("Vehicles are used for moving from one place to another ");
}
}
classCarextendsVehicle{
publicvoid move (){
super.move();// invokes the super class method
System.out.println("Car is a good medium of transport ");
}
}
publicclassTestCar{
publicstaticvoid main (Stringargs[]){
Vehicle b =newCar();// Vehicle reference but Car object
b.move();//Calls the method in Car class
}
}
Abstract Class
A class which contains the abstract keyword in its declaration is known as
abstract class.
Abstract classes may or may not contain abstract methods, i.e., methods
without body ( public void get(); )
But, if a class has at least one abstract method, then the class must be declared
abstract.
To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.
publicabstractclassEmployee{
privateString name;
privateString address;
privateint number;
publicdoublecomputePay(){
System.out.println("Inside Employee computePay");
return0.0;
}
publicvoidmailCheck(){
System.out.println("Mailing a check to "+this.name +" "+this.address);
}
publicStringtoString(){
return name +" "+ address +" "+ number;
}
publicStringgetName(){
return name;
}
publicStringgetAddress(){
return address;
}
publicvoidsetAddress(StringnewAddress){
address=newAddress;
}
publicintgetNumber(){
return number;
}
/* File name : AbstractDemo.java */
publicclassAbstractDemo{
publicstaticvoid main(String[]args){
/* Following is not allowed and would raise error */
Employee e =newEmployee("George W.","Houston, TX",43);
System.out.println("\n Call mailCheck using Employee reference--");
e.mailCheck();
}
}
ERROR:Employee is abstract; cannot be instantiated
publicvoidmailCheck(){
System.out.println("Within mailCheck of Salary class ");
System.out.println("Mailing check to "+getName()+" with salary "+ salary);
}
publicdoublegetSalary(){
return salary;
}
publicvoidsetSalary(doublenewSalary){
if(newSalary>=0.0){
salary=newSalary;
}
}
publicdoublecomputePay(){
System.out.println("Computing salary pay for "+getName());
return salary/52;
}
}
Here, you cannot instantiate the Employee class, but you can instantiate the
Salary Class, and using this instance you can access all the three fields and
seven methods of Employee class as shown below.
/* File name : AbstractDemo.java */
publicclassAbstractDemo{
publicstaticvoid main(String[]args){
Salary s =newSalary("MohdMohtashim","Ambehta, UP",3,3600.00);
Employee e =newSalary("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();
}
}
Output
Constructing an Employee
Constructing an Employee
Call mailCheck using Salary reference --
Within mailCheck of Salary class
Mailing check to MohdMohtashim with salary 3600.0
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 an abstract.
You have to place the abstract keyword before the method name in the method
declaration.
Instead of curly braces, an abstract method will have a semoi colon (;) at the
end.
Example
publicabstractclassEmployee{
privateString name;
privateString address;
privateint number;
publicabstractdoublecomputePay();
// Remainder of class definition
}
Suppose Salary class inherits the Employee class, then it should implement
the computePay() method as shown below −
publicdoublecomputePay(){
System.out.println("Computing salary pay for "+getName());
return salary/52;
}
// Remainder of class definition
}
Interface
An interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
An interface cannot contain instance fields. The only fields that can appear in an
interface must be declared both static and final.
Declaring Interfaces
The interface keyword is used to declare an interface. Here is a simple
example to declare an interface −
Example
Following is an example of an interface −
publicinterfaceNameOfInterface{
// Any number of final, static fields
// Any number of abstract method declarations\
}
An interface is implicitly abstract. You do not need to use the abstract keyword
while declaring an interface.
Each method in an interface is also implicitly abstract, so the abstract keyword
is not needed.
Example
/* File name : Animal.java */
interfaceAnimal{
publicvoid eat();
publicvoid travel();
}
Implementing Interfaces
When a class implements an interface, you can think of the class as signing
a contract, agreeing to perform the specific behaviors of the interface. If a
class does not perform all the behaviors of the interface, the class must
declare itself as abstract.
Example
/* File name : MammalInt.java */
publicclassMammalIntimplementsAnimal{
publicvoid eat(){
System.out.println("Mammal eats");
}
publicvoid travel(){
System.out.println("Mammal travels");
}
publicintnoOfLegs(){
return0;
}
publicstaticvoid main(Stringargs[]){
MammalInt m =newMammalInt();
m.eat();
m.travel();
}
}
Output
Mammal eats
Mammal travels
1) Abstract class can have abstract and non- Interface can have only abstract methods.
abstract methods.
2) Abstract class doesn't support multiple inheritance. Interface supports multiple inheritance.
3) Abstract class can have final, non-final, static and Interface has only static and final variables.
non-static variables.
4) Abstract class can have static methods, main Interface can't have static methods, main method
method and constructor. or constructor.
5) Abstract class can provide the implementation of Interface can't provide the implementation of
interface. abstract class.
6) The abstract keyword is used to declare abstract class. The interface keyword is used to declare
interface.
7) Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
Abstract class and interface both are used to achieve abstraction where we can declare the
abstract methods. Abstract class and interface both can't be instantiated.
But there are many differences between abstract class and interface that are given below.
Simply, abstract class achieves partial abstraction (0 to 100%) whereas interface achieves
fully abstraction (100%).
interface A{
void a();//bydefault, public and abstract
void b();
void c();
void d();
}
/Creating abstract class that provides the implementation of one method of A interface
abstract class B implements A{
public void c(){System.out.println("I am C");}
}
//Creating subclass of abstract class, now we need to provide the implementation of rest
of the methods
class M extends B{
public void a(){System.out.println("I am a");}
public void b(){System.out.println("I am b");}
public void d(){System.out.println("I am d");}
}
//Creating a test class that calls the methods of A interface
class Test5{
public static void main(String args[]){
A a=new M(); a.a(); a.b(); a.c(); a.d();
}}
Output:
I am a
I am b
I am c
I am d
1. interface Printable{
2. void print();
3. }
4.
5. interface Showable{
6. void show();
7. }
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
8. public void show(){System.out.println("Welcome");}
9.
10. public static void main(String args[]){
11. A7 obj = new A7();
12. obj.print();
13. obj.show();
14. }
15. }
16. Output:Hello
17. Welcome
Interface inheritance
A class implements interface but one interface extends another interface .
1. interface Printable{
2. void print();
3. }
4. interface Showable extends Printable{
5. void show();
6. }
7. class Testinterface2 implements Showable{
8.
9. public void print(){System.out.println("Hello");}
10. public void show(){System.out.println("Welcome");}
11.
12. public static void main(String args[]){
13. Testinterface2 obj = new Testinterface2();
14. obj.print();
15. obj.show();
16. }
17. }