0% found this document useful (0 votes)
3 views

chapter 5

Chapter 5 discusses key Object-Oriented Programming (OOP) concepts including encapsulation, inheritance, method overloading, method overriding, and polymorphism. Encapsulation involves wrapping data and methods in a class, while inheritance allows one class to inherit properties from another. Method overloading enables multiple methods with the same name but different parameters, and method overriding allows a subclass to provide a specific implementation of a method already defined in its parent class.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

chapter 5

Chapter 5 discusses key Object-Oriented Programming (OOP) concepts including encapsulation, inheritance, method overloading, method overriding, and polymorphism. Encapsulation involves wrapping data and methods in a class, while inheritance allows one class to inherit properties from another. Method overloading enables multiple methods with the same name but different parameters, and method overriding allows a subclass to provide a specific implementation of a method already defined in its parent class.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 25

Chapter 5

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

Encapsulation in java is a process of wrapping code and data together into a single unit, for
example capsule i.e. mixed of several medicines.

We can create a fully encapsulated class in java by making all the


data members of the class private. Now we can use setter and getter methods to set and get the
data in it.

It 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 defin

ed outside the class. Access to the data and code is tightly controlled by an interface.

Advantage of Encapsulation in java


 The fields of a class can be made read-only or write-only.
 A class can have total control over what is stored in its fields.
 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.

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;

1
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 accessed 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

2
2.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
super class except for the private properties of the super class.

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[]){

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

System.out.println(m instanceof Animal);


System.out.println(m 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 to 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);
}
}

4
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 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 inheritances.

Types of Inheritance

On the basis of class, there can be three types of inheritance: single, multilevel and hierarchical
in java.

In java programming, multiple and hybrid inheritance is supported through interface only. We
will learn about interfaces later.

5
Multiple inheritance is not supported in java in case of class.

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

6
3.Method Overloading
If a class has multiple methods by same name but different parameters, it is known
as Method Overloading.

If we have to perform only one operation, having same name of the methods increases the
readability of the program.

Suppose you have to perform addition of the given numbers but there can be any number of
arguments, if you write the method such as a(int,int) for two parameters, and b(int,int,int) for
three parameters then it may be difficult for you as well as other programmers to understand the
behavior of the method because its name differs. So, we perform method overloading to figure
out the program quickly.

Different ways to overload the method


There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In java, Method Overloading is not possible by changing the return type of the method.

1)Example of Method Overloading by changing the no. of arguments

In this example, we have created two overloaded methods, first sum method performs addition of
two numbers and second sum method performs addition of three numbers.

1. class Calculation{

7
2. void sum(int a,int b)
3. {
4. System.out.println(a+b);
5. }
6. void sum(int a,int b,int c)
7. {
8. System.out.println(a+b+c);
9. }
10. public static void main(String args[]){
11. Calculation obj=new Calculation();
12. obj.sum(10,10,10);
13. obj.sum(20,20);
14. }
15. }

Output:30
40

2)Example of Method Overloading by changing data type of argument

In this example, we have created two overloaded methods that differ in data type. The first sum
method receives two integer arguments and second sum method receives two double arguments.

1. class Calculation2{
2. void sum(int a,int b)
3. {
4. System.out.println(a+b);
5. }
6. void sum(double a,double b)
7. {
8. System.out.println(a+b);
9. }
10. public static void main(String args[]){
11. Calculation2 obj=new Calculation2();
12. obj.sum(10.5,10.5);
13. obj.sum(20,20);
14.
15. }
16. }

Output:21.0
40

8
Que) Why Method Overloaing is not possible by changing the return type of method?

In java, method overloading is not possible by changing the return type of the method because
there may occur ambiguity. Let's see how ambiguity may occur:

Because there was problem:

1. class Calculation3{
2. int sum(int a,int b)
3. {
4. System.out.println(a+b);
5. }
6. double sum(int a,int b)
7. {
8. System.out.println(a+b);
9. }
10.
11. public static void main(String args[]){
12. Calculation3 obj=new Calculation3();
13. int result=obj.sum(20,20); //Compile Time Error
14.
15. }
16. }

int result=obj.sum(20,20); //Here how can java determine which sum() method should be called

Can we overload main() method?

Yes, by method overloading. You can have any number of main methods in a class by method
overloading. Let's see the simple example:

1. class Overloading1{
2. public static void main(int a)
3. {
4. System.out.println(a);
5. }
6.
7. public static void main(String args[]){
8. System.out.println("main() method invoked");
9. main(10);
10. }
11. }

9
Output: main() method invoked
10

Method Overloading and Type Promotion

One type is promoted to another implicitly if no matching data type is found. Let's understand
the concept by the figure given below:

As displayed in the above diagram, byte can be promoted to short, int, long, float or double. The
short data type can be promoted to int, long, float or double. The char data type can be promoted
to int, long, float or double and so on.

Example of Method Overloading with TypePromotion


1. class OverloadingCalculation1{
2. void sum(int a,long b){System.out.println(a+b);}
3. void sum(int a,int b,int c){System.out.println(a+b+c);}
4.
5. public static void main(String args[]){
6. OverloadingCalculation1 obj=new OverloadingCalculation1();

10
7. obj.sum(20,20);//now second int literal will be promoted to long
8. obj.sum(20,20,20);
9.
10. }
11. }

Output:40
60

Example of Method Overloading with TypePromotion if matching found

If there are matching type arguments in the method, type promotion is not performed.

1. class OverloadingCalculation2{
2. void sum(int a,int b){System.out.println("int arg method invoked");}
3. void sum(long a,long b){System.out.println("long arg method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation2 obj=new OverloadingCalculation2();
7. obj.sum(20,20);//now int arg sum() method gets invoked
8. }
9. }

Output:int arg method invoked

Example of Method Overloading with TypePromotion in case ambiguity

If there are no matching type arguments in the method, and each method promotes similar
number of arguments, there will be ambiguity.

1. class OverloadingCalculation3{
2. void sum(int a,long b){System.out.println("a method invoked");}
3. void sum(long a,int b){System.out.println("b method invoked");}
4.
5. public static void main(String args[]){
6. OverloadingCalculation3 obj=new OverloadingCalculation3();
7. obj.sum(20,20);//now ambiguity
8. }
9. }

11
Output:Compile Time Error

4.Method Overriding
If subclass (child class) has the same method as declared in the parent class, it is known
as method overriding.

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.

Advantage 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 Method Overriding


 Method must have same name as in the parent class
 Method must have same parameter as in the parent class.
 Instance methods can be overridden only if they are inherited by the subclass.
 A method declared final cannot be overridden.
 A method declared static cannot be overridden but can be re-declared.
 If a method cannot be inherited, then it cannot be overridden.
 A subclass within the same package as the instance's superclass can override any superclass
method that is not declared private or final.
 A subclass in a different package can only override the non-final methods declared public or
protected.
 An overriding method can throw any uncheck exceptions, regardless of whether the overridden
method throws exceptions or not. However the overriding method should not throw checked
exceptions that are new or broader than the ones declared by the overridden method. The
overriding method can throw narrower or fewer exceptions than the overridden method.
 Constructors cannot be overridden.

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() {
3. System.out.println("Vehicle is running");
12
4. }
5. }
6. class Bike2 extends Vehicle{
7. void run() { System.out.println("Bike is running safely"); }
8.
9. public static void main(String args[]){
10. Bike2 obj = new Bike2();
11. obj.run();
12. }

Output: Bike is running safely

Using the super keyword:


When invoking a superclass version of an overridden method the super keyword is used.
class Animal{

public void move(){


System.out.println("Animals can move");
}
}
class Dog extends Animal{

public void move(){


super.move(); // invokes the super class method
System.out.println("Dogs can walk and run");
}
}
public class TestDog{

public static void main(String args[]){

Animal b = new Dog(); // Animal reference but Dog object


b.move(); //Runs the method in Dog class

}
}

This would produce the following result:

Animals can move


Dogs can walk and run

What is the difference between method Overloading and Method Overriding?


There are three basic differences between the method overloading and method overriding. They
are as follows:

Method Overloading Method Overriding

13
1) Method overloading is used to increase Method overriding is used to provide the specific
the readability of the program. implementation of the method that is already provided by
its super class.
2) Method overloading is performed Method overriding occurs in two classes that have IS-A
within a class. relationship.
3) In case of method overloading In case of method overriding parameter must be same.
parameter must be different.

5.Polymorphism
The word ‘polymorphism’ literally means ‘a state of having many shapes’ or ‘the capacity to
take on different forms’. When applied to object oriented programming languages like Java, it
describes a language’s ability to process objects of various types and classes through a single,
uniform interface.

Polymorphism in Java has two types: Compile time polymorphism (static binding) and Runtime
polymorphism (dynamic binding). Method overloading is an example of static polymorphism,
while method overriding is an example of dynamic polymorphism.

An important example of polymorphism is how a parent class refers to a child class object. In
fact, any object that satisfies more than one IS-A relationship is polymorphic in nature.

For instance, let’s consider a class Animal and let Cat be a subclass of Animal. So, any
cat IS animal. Here, Cat satisfies the IS-A relationship for its own type as well as its super
class Animal.

Note: It’s also legal to say every object in Java is polymorphic in nature, as each one passes an
IS-A test for itself and also for Object class.

Static Polymorphism:

In Java, static polymorphism is achieved through method overloading. Method overloading


means there are several methods present in a class having the same name but different
types/order/number of parameters.

At compile time, Java knows which method to invoke by checking the method signatures. So,
this is called compile time polymorphism or static binding. The concept will be clear from the
following example:

class DemoOverload{

14
public int add(int x, int y){ //method 1

return x+y;

public int add(int x, int y, int z){ //method 2

return x+y+z;

public int add(double x, int y){ //method 3

return (int)x+y;

public int add(int x, double y){ //method 4

return x+(int)y;

class Test{

public static void main(String[] args){

DemoOverload demo=new DemoOverload();

System.out.println(demo.add(2,3)); //method 1 called

System.out.println(demo.add(2,3,4)); //method 2 called

System.out.println(demo.add(2,3.4)); //method 4 called

System.out.println(demo.add(2.5,3)); //method 3 called

In the above example, there are four versions of add methods. The first method takes two
parameters while the second one takes three. For the third and fourth methods there is a change
of order of parameters. The compiler looks at the method signature and decides which method to
invoke for a particular method call at compile time.

Dynamic Polymorphism:

15
Suppose a sub class overrides a particular method of the super class. Let’s say, in the program
we create an object of the subclass and assign it to the super class reference. Now, if we call the
overridden method on the super class reference then the sub class version of the method will be
called.

Have a look at the following example.

class Vehicle{

public void move(){

System.out.println(“Vehicles can move!!”);

}}

class MotorBike extends Vehicle{

public void move(){

System.out.println(“MotorBike can move and accelerate too!!”);

}}

class Test{

public static void main(String[] args){

Vehicle vh=new MotorBike();

vh.move(); // prints MotorBike can move and accelerate too!!

vh=new Vehicle();

vh.move(); // prints Vehicles can move!!

It should be noted that in the first call to move(), the reference type is Vehicle and the object
being referenced is MotorBike. So, when a call to move() is made, Java waits until runtime to
determine which object is actually being pointed to by the reference. In this case, the object is of
the class MotorBike. So, the move() method of MotorBike class will be called. In the second call
to move(), the object is of the class Vehicle. So, the move() method of Vehicle will be called.

As the method to call is determined at runtime, this is called dynamic binding or late binding.

6.Abstraction

16
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;
}

17
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()

18
{
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("James Gosling", "Indonesia", 3, 3600.00);
Employee e = new Salary("John Adams", "Boston", 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

19
Mailing check to James Gosling 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()

20
{
System.out.println("Computing salary pay for " + getName());
return salary/52;
}

//Remainder of class definition


}

21
7.Interfaces
An interface is a collection of abstract methods. A class implements an interface, thereby
inheriting the abstract methods of the interface.

An interface is not a class. Writing an interface is similar to writing a class, but they are two
different concepts. A class describes the attributes and behaviors of an object. An interface
contains behaviors that a class implements.

Unless the class that implements the interface is abstract, all the methods of the interface need to
be defined in the class.

An interface is similar to a class in the following ways:

 An interface can contain any number of methods.


 An interface is written in a file with a .java extension, with the name of the interface matching
the name of the file.
 The bytecode of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a directory
structure that matches the package name.

However, an interface is different from a class in several ways, including:

 You cannot instantiate an interface.


 An interface does not contain any constructors.
 All of the methods in an interface are abstract.
 An interface cannot contain instance fields. The only fields that can appear in an interface must
be declared both static and final.
 An interface is not extended by a class; it is implemented by a class.
 An interface can extend multiple interfaces.

Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface:
Example:
Let us look at an example that depicts encapsulation:

/* File name : NameOfInterface.java */


import java.lang.*;
//Any number of import statements

public interface NameOfInterface


{
//Any number of final, static fields
//Any number of abstract method declarations\
}

22
Interfaces have the following properties:

 An interface is implicitly abstract. You do not need to use the abstract keyword when declaring
an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
 Methods in an interface are implicitly public.

Example:
/* File name : Animal.java */
interface Animal {

public void eat();


public void 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.

A class uses the implements keyword to implement an interface. The implements keyword
appears in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal{

public void eat(){


System.out.println("Mammal eats");
}

public void travel(){


System.out.println("Mammal travels");
}

public int noOfLegs(){


return 0;
}

public static void main(String args[]){


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

This would produce the following result:

Mammal eats
Mammal travels
23
When overriding methods defined in interfaces there are several rules to be followed:

 Checked exceptions should not be declared on implementation methods other than the ones
declared by the interface method or subclasses of those declared by the interface method.
 The signature of the interface method and the same return type or subtype should be maintained
when overriding the methods.
 An implementation class itself can be abstract and if so interface methods need not be
implemented.

When implementation interfaces there are several rules:

 A class can implement more than one interface at a time.


 A class can extend only one class, but implement many interfaces.
 An interface can extend another interface, similarly to the way that a class can extend another
class.

Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits the
methods of the parent interface.
The following Sports interface is extended by Hockey and Football interfaces.

//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}

//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}

//Filename: Hockey.java
public interface Hockey extends Sports
{
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}

24
The Hockey interface has four methods, but it inherits two from Sports; thus, a class that
implements Hockey needs to implement all six methods. Similarly, a class that implements
Football needs to define the three methods from Football and the two methods from Sports.

Extending Multiple Interfaces:


A Java class can only extend one parent class. Multiple inheritance is not allowed. Interfaces are
not classes, however, and an interface can extend more than one parent interface.

The extends keyword is used once, and the parent interfaces are declared in a comma-separated
list.

For example, if the Hockey interface extended both Sports and Event, it would be declared as:

public interface Hockey extends Sports, Event

25

You might also like