Você está na página 1de 39

Java Programming

Chapter 7
INHERITANCE

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Agenda
 7.1 Basics of Inheritance
 7.2 Inheriting and Overriding superclass Methods
 7.3 Calling superclass Constructor
 7.4. polymorphism
 7.5 Classes that Inherit from Different Classes
 7.6 Abstract Classes
 7.7 Final Class

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Introduction
 Inheritance is the mechanism for instances of the
subclass to access the superclass variables and
methods.
 It is the practice where one object obtains the
properties of another object.
 With the help of inheritance, the information is
manageable through a hierarchical order.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
7.1 Basics of Inheritance
 Inheritance is the process by which one object can obtain the properties of
another object.
 This is significant as all Java classes are arranged in a hierarchical
classification. For instance, Hierarchical classification of Food is given
in fig 7.1

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Superclass and Subclass
 superclass is an elevated class that supplies its attributes and methods to
the ladder of subclasses.
 Subclass is an object class that is derived from a superclass, from which it
inherits the base set of properties and methods.
 Inheritance involves a superclass and a subclass. The superclass is the
general class and the subclass is a specialized class. The subclass is an
extended version of the superclass.
 The subclass inherits fields and methods from the superclass without any
of them being rewritten.
 Furthermore, new fields and methods can be added to the subclass to
make it more specialized than the superclass. When one object is a
specialized version of another object, there is an “is a” relationship
between them.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
is-a Relationship
 Here are a few other examples of
an “is a” relationship.
 A car is a vehicle.
 A flower is a plant.
 A rectangle is a shape
 Fig 7.2 shows the Unified
Modeling Language (UML)
diagram for the Payment and
Cheque classes, which are
designed to hold variables and
methods in the context of ‘is-a’
Relationship.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
is-a Relationship (Contd.)
 Let us see how extends keyword is  Now, based on the above example,
used to achieve inheritance. The in OO terms, the following are true:
extends keyword is used to inherit the  Fruit is a superclass of Apple
properties of a class. subclass.
 The syntax of extends keyword is  Fruit is a superclass of Orange
given in the following example. subclass. Apple and Orange are the
public class Fruit
{
subclasses which are deriving the
… member variables and methods of
} Fruit superclass using extends
public class Apple extends Fruit
{
keyword.

}
public class Orange extends Fruit
{

}

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.1 illustrates the concept of inheritance.
class Fruit public class FruitExample
{ {
String color;
public static void main(String[]
String name;
args)
public void fruitdetails
{
(String name,String color)
{ Apple obj=new Apple();
System.out.println obj.fruitdetails("Ooty Apple", "red
("Nameofthefruit:="+name); yellow");
System.out.println("Color of the obj.printdetail();
fruit:="+color); }
} }
}
class Apple extends Fruit
{ Output 7.1
String benefit="Good for Heart"; Name of the fruit:=Ooty Apple
public void printdetail()
Color of the fruit:=red yellow
{
Health benefit:=Good for Heart
System.out.println("Health
benefit:="+benefit);
}
}

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.4 illustrates the same concept of Overriding the method of superclass
class company public void printcompany()
{ {
System.out.println(“Company Name:”+name);
String sector;
System.out.println(“Sector:”+sector);
String name; S y s t e m . o u t . p r i n t l n ( “ C
String headoffice; o m p a n y
public void printcompany() Headoffice:”+headoffice);
{ }
public void printbranch()
System.out.println(“Company
{
Details”);
System.out.println(“Branch name:”+bname);
}
System.out.println(“Place of
} Branch:”+place);
class Branch extends company }
{ } Output 7.4
Company Name:Wipro
String bname; Sector:IT and Services
String place; Company Headoffice:Bangalore
Branch name:Chennai TechPark
Place of Branch:Solinganallur

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
7.2 Inheriting and Overriding Superclass Methods
 When defining methods in the subclass, there is a need to use any one the
three following scenarios:
 1. First scenario is as simple as inheriting the methods of the superclass;
when all methods defined in the superclass are automatically inherited by
the subclass.
 2. Defining new methods in the subclass; when the methods of the
superclass are not enough to provide the functionalities. Then, defining of
new methods in the subclass is the best way.
 3. Overriding the methods which are defined in the superclass. Defining a
method in a subclass, the method name and its arguments are of the same
type as of a superclass method. Now the subclass method will override the
superclass method. In this scenario, when the method is invoked by the
subclass object, only the subclass method will be executed (superclass
method is overridden).

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.2. First and second scenario example program
//Vehicle is a superclass class Car extends Vehicle public class
and Car is a { SimpleInheritance
subclass. String fueltype; {
//Simple Inheritance: A String color; public static void
Car is a Vehicle public void main(String[] args)
class Vehicle PrintCarDetails()
{ {
{ System.out.println(“Car Car obj=new Car();
String brandname; Details”); obj.brandname=”BMW”;
double price; S y s t e m . o u t . p r obj.price=3999999.0;
public void i n t l n ( “ C a obj.fueltype=”petrol”;
PrintVehicleDetails() rfueltype:”+fueltype);
System.out.println(“Car obj.color=”Red”;
{ obj.PrintVehicleDetails();
Color:”+color);
System.out.println(“Vehicl } obj.PrintCarDetails();
e Details”);
} }
System.out.println(“ Brand
of } Output 7.2
Vehicle:”+brandname); Vehicle Details
System.out.println(“ Price Brand of Vehicle:BMW
of Vehicle:”+price); Price of Vehicle:3999999.0
Car Details
}
Car fueltype:petrol
} Car Color:Red

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Overriding the Superclass Method
 Inheriting the method enables the class Vehicle public class
programmer to define and use { OverridingMethods
public void PrintDetails() {
methods repeatedly in subclasses public static void
{
without having to define the System.out.println(“Vehicle main(String[] args)
methods again in the subclass. Details”); {
} } Car obj=new Car();
 When the program needs an object obj.fueltype=”petrol”;
class Car extends Vehicle
to present the same method obj.color=”Red”;
{
obj.PrintDetails();
available in both superclass and String fueltype; }
subclass but the methods have String color; }
different behavior. public void PrintDetails()
{
 The subclass method that has the System.out.println(“Car Output 7.3
same name, same arguments and Details”);
Car Details
S y s t e m . o u t . p r i
same return type as a method in n t l n ( “ C a r Car fueltype:petrol
the superclass. That means, the fueltype:”+fueltype); Car Color:Red
superclass method is overridden by System.out.println(“Car
the subclass, and this is called Color:”+color);
}
overriding. This concept is }
illustrated in Program 7.3.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Super Keyword
 In some situations, there is a need to class Car extends Vehicle
invoke the overridden method of the {
String fueltype;
superclass, and this can be done with String color;
the help of the keyword super. The public void PrintDetails()
general form to invoke an { super.PrintDetails();
overridden method is given below. System.out.println(“Car Details”);
S y s t e m . o u t . p r i n t l n ( “ C
 super.methodname(args); a r fueltype:”+fueltype);
System.out.println(“Car Color:”+color);
 As was the case in the previous } }
program, the super.PrintDetails() public class OverridingMethods
statement has been included inside {
the subclass method definition. public static void main(String[] args)
{
 Program 7.5 illustrates this concept. Car obj=new Car();
class Vehicle obj.fueltype=”petrol”;
{ public void PrintDetails() obj.color=”Red”;
{ obj.PrintDetails();
System.out.println(“Vehicle Details”); }}
} }

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.6 also illustrates super keyword
class company public void printbranch()
{ {
String sector; System.out.println(“Branch name:”+bname);
String name; System.out.println(“Place of
String headoffice; Branch:”+place);
public void printcompany() } }
{ System.out.println(“*****Company public class overridesuper2
Details*****”); { public static void main(String[] args)
} } { Branch b=new Branch();
class Branch extends company b.name=”Wipro”;
{ b.sector=”IT and Services”;
String bname; b.headoffice=“Bangalore”;
String place; b.bname=“Chennai TechPark “;
public void printcompany() b.place=“solinganallur”;
{ super.printcompany(); b.printcompany();
System.out.println(“Company Name:”+name); b.printbranch();
System.out.println(“Sector:”+sector); }
S y s t e m . o u t . p r i n t l n ( “ C }
o m p a n y
Headoffice:”+headoffice);
}

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
7.3 Calling Superclass Constructor
 The state and behavior of a class are  Here, x is the superclass of y, so the
defined not only by that class but also constructor of x is x(int i), and it should be
invoked before the constructor of y is
by its superclass. Therefore, in order to
invoked. Hence, the superclass constructor
initialize an object of a class, it is can be invoked by using the super keyword
necessary to execute the constructor of inside the subclass constructor of y which has
its superclass. the following form:
 The proper way of initializing subclass  super(i);
constructors in the subclass, is to first  Then, the above code for subclass is changed
invoke the superclass constructor. For to the following form:
instance,
class y extends x
class x
{ {
x(int i )
y( )
{…}
} {
class y extends x super(i);
{
y( ) }
{…} }
}


This has been illustrated in Program 7.7.
J

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.7
//Code to illustrate super() public class SimpleInheritance
class superclass {
{
public static void
String s=”Hello”; main(String[] args)
public superclass()
{
{
System.out.println(“superclass
subclass obj=new subclass();
method:”+s); }
} }
}
class subclass extends superclass
Output 7.7
{
superclass method: Hello
String s1=”Inheritance”;
public subclass()
subclass method:
{ Inheritance
super();
System.out.println(“subclass
method:”+s1);
}
}
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.8 illustrates the same concept.
class college super();
{ System.out.println(“Department
String name=”Arts and Science name:”+dname);
College”; }
String status=”Autonomous”; }
public college() public class superconstructordemo
{ {
System.out.println(“Name of public static void main(String[]
college:”+name); args)
System.out.println(“Status of {
college:”+status); department d=new
} department(“Computer Science”);
} }
class department extends college }
{
String dname;
Output 7.8
Name of college: Arts and Science College
public department(String dname)
Status of college: Autonomous
{ Department name: Computer Science

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
7.4. Polymorphism
 Polymorphism is the perception of executing a single action
in different ways. Polymorphism is derived from Greek
words: poly and morphs. The word “poly” means many and
“morphs” means forms. Polymorphism means ‘many forms’.
 There are two types of polymorphism in Java: compile time
polymorphism and runtime polymorphism.
 It can be carried out by using method overloading and method
overriding concept. Method overriding is resolved at compile
time by invoking those methods within the subclass using
super keyword.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Overloading Method
 In method overloading, one or more methods have the same
name but different parameters as arguments for the methods.
That means, the method name is same but number of
signatures or arguments, return type, type of arguments, and
order of arguments are different.
 Overloaded methods can appear within the same class. In the
context of inheritance, a method in the subclass can overload
a method of the superclass or another method of the same
class. Overloading methods can be invoked in one of two
ways:
 Static binding
 Dynamic binding

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Static Binding
 The general structure of overloading methods between superclass and
subclass is given below.
class X
{
public void method1(String a)
{ }
}
class Y extends X
{
public void method1(int a)
{ }
public int method1(int a, int b)
{ }
}

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
This concept is illustrated below in Program 7.9 .
//Overloading concept with static binding class square extends shapes
//superclass {
class shapes square(int a)
{ { this.a = a; }
int a, r; public void calculate(int a)
double area; { area = a * a;
public void calculate() System.out.println(“Area of square:=” +
{ System.out.println(“Area of circle and area);
square”); } }
} } public class OverloadingExample
class circle extends shapes {public static void main(String[] args)
{ {
final double pi = 3.14; circle obj = new circle(3);
circle(int r) obj.calculate();
{ this.r = r; } obj.calculate(obj.r);
public void calculate(int r) square s = new square(4);
{ s.calculate(s.a);
}
area = pi * r * r; Output 7.9
} Area of circle and square
System.out.println(“Area of circle:=”
Area of circle:=28.259999999999998
+ area); } } Area of square:=16.0

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Runtime Polymorphism or Dynamic Binding
class shapes
 Runtime polymorphism or { int r=3;
Dynamic Method Dispatch is a double area;
process in which a call to an public void calculate()
{ System.out.println(“Area of circle:”);
overridden method is resolved at } }
runtime rather than at compile- class circle extends shapes
{ final double pi = 3.14;
time. public void calculate()
 In this process, an overridden { area = pi * r * r;
System.out.println(“Area of circle:=” +
method is called through the area); }
reference variable of a }
public class OverloadingExample
superclass. { public static void main(String[] args)
 The determination of the method { shapes obj = new circle();
obj.calculate();
to be called is based on the object }
being referred by the reference }
variable. This concept is
illustrated in Program 7.10.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Overloading vs. Overriding
Overloading Overriding
 When a method has the same  When a method overrides another
name as one or more other method, however, they both have
methods but a different the same signature.
parameter list, then it is a case of  A method cannot override another
overloading. method in the same class.
 Although overloaded methods  When a subclass overrides a
have the same name, they have superclass method, only the
different signatures. subclass’s version of the method
 Overloaded methods can appear can be called with a subclass
within the same class or a object.
method in a subclass can
overload a method in the
superclass.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
7.5 Classes that Inherit from Different Classes
 A class can inherit the properties 7.5.1 Single Inheritance
and methods from various  The properties and methods of a
classes like one superclass for base class are derived by a
subclass or more than one subclass, and this is called single
subclass for a superclass or inheritance.
nested subclasses for a  For instance, in Fig 7.3. Class A
superclass. is the base class and Class B is
 Java provides various types of the subclass.
inheritance such as
 Single inheritance
 Multilevel inheritance
 Hierarchical inheritance

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.11 illustrates single inheritance. A subclass derives the members of the base class.
// Single inheritance Example public void setChequeType(String
//Base Class chequeType)
class payment { ChequeType = chequeType; }
{ private int paymentId; }
private double amount; //Main Class to invoke methods using
public int getPaymentId() objects
{ return paymentId; } public class SingleInheritance
public void setPaymentId(int paymentId) { public static void main(String[] args)
{ this.paymentId = paymentId; } { Cheque c1=new Cheque();
public double getAmount() c1.setPaymentId(15);
{ return amount; } c1.setAmount(2600);
public void setAmount(double amount) c1.setChequeType(“ICICI”);
{ this.amount = amount; } System.out.println(“Payment
Id:”+c1.getPaymentId());
}
System.out.println(“Payment
//subclass cheque Amount:”+c1.getAmount());
class Cheque extends payment System.out.println(“Payment Cheque
{ Type:”+c1.getChequeType());
private String ChequeType; } Output 7.11
public String getChequeType() } Payment Id:15
{ return ChequeType; } Payment Amount:2600.0
Payment Cheque Type:ICICI

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
7.5.2 Multilevel Inheritance
 Here, the base class is derived by the subclass and the derived class
inherited by another subclass one after another. It is a ladder or hierarchy
of single level inheritance.
 This means if Class A is extended by class B and then class C further
extends class B, then the whole structure is termed as multilevel
inheritance.
 The pictorial representation of multilevel inheritance is given in Fig 7.4.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.12 illustrates multilevel inheritance.
// Multilevel inheritance public void setChequeType(String
//Base Class chequeType)
class payment {
{ ChequeType = chequeType;
private int paymentId; }
private double amount; }
public int getPaymentId() //inheriting from subclass cheque
{ return paymentId; } class CreditCard extends Cheque
public void setPaymentId(int paymentId) {
{ this.paymentId = paymentId; } private String CreditCardType;
public double getAmount() public String getCreditCardType()
{ return amount; } {
public void setAmount(double amount) return CreditCardType;
{ this.amount = amount; } }
} public void setCreditCardType(String
//subclass from base class creditCardType)
class Cheque extends payment {
{ CreditCardType = creditCardType;
private String ChequeType; }
public String getChequeType() }
{ return ChequeType; }

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.12 (Contd.)
public class multilevel
{
public static void main(String[] args)
{
CreditCard c1=new CreditCard();
c1.setPaymentId(15); //base class method
c1.setAmount(2600); //base class method
c1.setChequeType(“ICICI”); // subclass method
c1.setCreditCardType(“VISA”); // subclass from another sub method
System.out.println(“Payment Id:”+c1.getPaymentId());
System.out.println(“Payment Amount:”+c1.getAmount());
System.out.println(“Payment Cheque Type:”+c1.getChequeType());
System.out.println(“Payment Credit card Type:”+c1.getCreditCardType());
}
}
Output 7.12
Payment Id:15
Payment Amount:2600.0
Payment Cheque Type:ICICI
Payment Credit card
Type:VISA

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
7.5.3 Hierarchical Inheritance
 The superclass properties and methods can be inherited by multiple
subclasses. That means many subclasses can derive the properties of one
base class.
 Fig.7.5 illustrates this concept.
 The father is the base class and his three children are the subclasses. The
children have the characteristics of their father. So they are inheriting the
father’s properties and behaviors.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.13 illustrates the hierarchical inheritance.
// Hierarchical inheritance public void setChequeType(String
//Base Class chequeType)
class payment { ChequeType = chequeType; }
{ }
private int paymentId; //Another sub calss for same base class
private double amount; class CreditCard extends payment
public int getPaymentId() {
{ return paymentId; } private String CreditCardType;
public void setPaymentId(int paymentId) public String getCreditCardType()
{ this.paymentId = paymentId; } {
public double getAmount() return CreditCardType;
{ return amount; } }
public void setAmount(double amount) public void setCreditCardType(String
{ this.amount = amount; } creditCardType)
} {
//subclass CreditCardType = creditCardType;
class Cheque extends payment }
{ }
private String ChequeType;
public String getChequeType()
{ return ChequeType; }

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.13 (Contd.)
public class Hierarchical
{
public static void main(String[] args)
{
Cheque c1=new Cheque();
c1.setPaymentId(2);
c1.setAmount(5000);
c1.setChequeType(“ICICI”);
System.out.println(“Cheque Id:”+c1.getPaymentId());
System.out.println(“Cheque Amount:”+c1.getAmount()); Output 7.13
System.out.println(“Cheque Type:”+c1.getChequeType()); Cheque Id:2
CreditCard c=new CreditCard(); Cheque Amount:5000.0
c.setPaymentId(1); Cheque Type:ICICI
c.setAmount(26000); Creditcard Id:1
c.setCreditCardType(“VISA”); Creditcard Amount:26000.0
System.out.println(“Creditcard Id:”+c.getPaymentId()); Credit card Type:VISA
System.out.println(“Creditcard Amount:”+c.getAmount());
System.out.println(“Credit card Type:”+c.getCreditCardType());
}
}

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
7.6 Abstract Classes
 Abstraction is a process of hiding the implementation details and showing
only functionality to the user.
 In other words, it shows only important things to the user and hides the
internal details. Abstraction agrees to focus on what the object does
instead of how it does it.
 Abstract methods are usually declared when two or more subclasses are
expected to do a similar job in different ways through different
implementations.
 These subclasses extend the same Abstract class and provide different
implementations for the abstract methods.
 There are two ways to achieve abstraction in Java.
 Abstract class
 Interface

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Abstract Classes (Contd.)
 A class stated with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (method with body).
 Simply stated, an abstract class is a class with a missing method body. The
missing bodies are supplied by subclasses that extend the abstract class.
 A method that is declared as abstract and does not have an implementation
is known as an abstract method.
 Program 7.14 illustrates abstract classes and abstract methods.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.14
abstract class Person class PersonWithInt extends Person
{ { private int address;
private String name; public PersonWithInt(String the_name, int
public Person(String n) the_addr)
{ name = n; } { super(the_name);
public String getName() address = the_addr; }
{ return name; } public String getAddress()
public abstract String getAddress(); { return “ “ + address; }
} }
class PersonAddress extends Person public class abstractexample
{ { public static void main(String[] args)
private String address; {
public PersonAddress(String the_name, PersonAddress a=new PersonAddress(“jose”,
String the_addr) “chennai”);
{ Output 7.14 PersonWithInt p=new PersonWithInt(“Joel”,
super(the_name); Joel 277);
address = the_addr; 277 System.out.println(p.getName());
} Jose System.out.println(p.getAddress());
public String getAddress() chennai System.out.println(a.getName());
{ return address; } System.out.println(a.getAddress());
} } }

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.15
//abstract class and abstract method
abstract class Bike
{
abstract void getDetails(); // no implementation
}
class pulsar extends Bike
{
void getDetails()
{ Output 7.15
System.out.println(“Pulsar Black”); Pulsar Black
System.out.println(“ Rs.75000”); Rs.75000
}
public static void main(String args[])
{
Bike obj = new pulsar();
obj.getDetails();
}
}

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
7.7 Final Class
 The scope of the variables and methods in one class that can be accessed
by other classes can be determined by Access Specifiers or Modifiers.
 Different types of Modifiers are available in Java. In the following section,
final modifier is explained with an example.
 A class that is declared with the final modifier cannot be inherited by other
classes. This means that such a class cannot have any subclass. Also, the
methods in such a class cannot be overridden.
 Sometimes, there is a need to define a class in such a way that the methods
implemented by that class cannot be overridden. Such a class is declared
with the final modifier. The abstract and final modifiers are not used
simultaneously.
 A class is declared with final keyword as in the general form. If the class is
declared with final, this class cannot be derived by the subclasses.

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.16 illustrates this concept.
final class UGcourse
{
String name;
void display(String name)
{
System.out.println(“UG Department:”+name);
}
}
class PGcourse extends UGcourse //Error cannot inherit from final class
{
void display()
{
Output 7.16
System.out.println(“MCA,M.Sc”); Exception in thread “main”
} java.lang.VerifyError:
} Cannot inherit from final
public class Departments
{
class
public static void main(String[] args)
{
PGcourse p=new PGcourse();
p.display();
}
}
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Program 7.16 (Contd.)
 The base class cannot be final class PGcourse extends UGcourse
{
declared as final whereas final void display()
methods can be defined in the {
class. The subclass may be System.out.println(“MCA,M.Sc”);
declared as final class and it can }
inherit the base class properties }
public class Departments
and final methods.
{
 Program 7.17 illustrates this. public static void main(String[]
class UGcourse args)
{ {
String name; PGcourse p=new PGcourse();
final void display(String name) p.display(“B.Sc CS”);
{ p.display();
System.out.println(“UG } Output 7.17
Department:”+name); } UG Department:B.Sc CS
} MCA,M.Sc
}

Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi
Java Programming © Universities Press (India) Private Limited Sagayaraj, Denis, Karthik, Gajalakshmi

Você também pode gostar