0% found this document useful (0 votes)
21 views40 pages

Chapter 5

The document provides an overview of inheritance in Java, explaining the concepts of superclass and subclass, and the advantages of code reuse. It details various types of inheritance such as single, multilevel, hierarchical, and notes that multiple inheritance is not supported directly in Java. Additionally, it covers polymorphism, method overloading, constructor overloading, and the use of packages in Java programming.

Uploaded by

zohosaravanan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
21 views40 pages

Chapter 5

The document provides an overview of inheritance in Java, explaining the concepts of superclass and subclass, and the advantages of code reuse. It details various types of inheritance such as single, multilevel, hierarchical, and notes that multiple inheritance is not supported directly in Java. Additionally, it covers polymorphism, method overloading, constructor overloading, and the use of packages in Java programming.

Uploaded by

zohosaravanan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Using Classes 5.

Using Classes
5.1 Introduction to Inheritance
A process of creating a new class from existing class and the features of the
existing class are available to the new class is called inheritance.

 The existing class is called superclass (or) base class (or) parent class.
 The newly created class is called subclass (or) derived class (or) child
class.

Advantage of inheritance is reusing the code from the super class to sub class
without rewriting the same coding again.

Inheritance allows subclass to access variables and methods of their superclass.

Defining a Subclass
Syntax

class subclassname extends superclassname


{
//variable declaration;
//method declaration;
}
The keyword extends represent superclass was inherited by subclass, so the
variable and methods can be accessed directly in the sub class.

5.2 IS-A Relationship


Inheritance has IS A Relationship
Example
class lion extends animal //represent as lion IS-A animal
class crow extends bird // represent as crow IS-A bird

bird vehicle

crow car
Figure 5.1 IS-A Relationship

using instanceof ,we can assure that object belongs to the particular class, if you
pass wrong (object or class) it will show error
5.2 Java Programming Paradigms

class bird
{ }
class crow extends bird //
crow inherited from class bird
{ }
class vehicle
{ }
class car
{ }
class checkISA
{
public static void main(String args[])
{
bird b=new bird();
vehicle v=new vehicle();
crow co=new crow();
car ca=new car();
System.out.println(b instanceof bird); //assure the object belong to classs
System.out.println(v instanceof vehicle);
System.out.println(co instanceof crow);
System.out.println(ca instanceof car);
}
}
Program 5.1 Example for IS-A Relationship
Output
I:\java\graphics>javac checkISA.java
I:\java\graphics>java checkISA
true
true
true
true

5.3 Types of inheritance


o Single inheritance
o Multilevel inheritance
o Hierarchical inheritance
o Multiple inheritance

5.4 Single inheritance


The process of deriving a new class from existing class is called single inheritance.
Syntax
The keyword extends will be used in the subclass declaration
Using Classes 5.3

class Super
{
----- Super
-----
}

class SubSuper extends super


{
----- Sub
-----
}

class Super
{
int A=5;
void AddA()
{
System.out.println("AddA(A+A)="+(A+A));
}
}
class Sub extends Super
{
int B=10;
void AddAB()
{ Super
AddA();
System.out.println("AddAB(A+B)="+(A+B));
}
}
class SingleInheritance
{ Sub
public static void main(String args[])
{
Sub subobject=new Sub();
subobject.AddAB();
}
}
Program 5.2 Example program for single inheritance
Output:
I:\java\OOPS>javac SingleInheritance.java
I:\java\OOPS>java SingleInheritance
5.4 Java Programming Paradigms

AddA(A+A)=10
AddAB(A+B)=15

5.5 Multilevel inheritance


Deriving a new class from already derived class is called multilevel inheritance
It also represented by use of derived class as a super class.

Syntax
class Super
{
-----
----- Super
}

class SubSuper extends super


{ SubSuper
-----
-----
}
class Sub extends SubSuper
{ Sub
-----
-----
}

class Super
{
int A=5; AddA
void AddA()
{
System.out.println("AddA(A+A)="+(A+A));
}
} AddAB
class SubSuper extends Super
{
int B=10;
void AddAB()
{ AddABC
System.out.println("AddAB(A+B)="+(A+B));
}
Using Classes 5.5

}
class Sub extends SubSuper
{
void AddABC()
{
int C=15;
AddA();
AddAB();
System.out.println("AddABC(A+B+C)="+(A+B+C));
}
}
class MultiLevelInheritance
{
public static void main(String args[])
{
Sub subobject=new Sub();
subobject.AddABC();
}
}
Program 5.3 Example for multilevel inheritance
Output
I:\java\OOPS>javac MultiLevelInheritance.java
I:\java\OOPS>java MultiLevelInheritance
AddA(A+A)=10
AddAB(A+B)=15
AddABC(A+B+C)=30

5.6 Hierarchical inheritance


If a super class has more than one sub class is called hierarchical inheritance.

SuperA
AddA()

SubB SubC
AddAB() AddAC()

Figure 5.2 Hierarchical Inheritance


5.6 Java Programming Paradigms

class SuperA
{
int A=5;
void AddA()
{
System.out.println("The value of AddA="+(A+A));
}
}
class SubB extends SuperA
{
int B=10;
void AddAB()
{
System.out.println("The value of AddAB="+(A+B));
}
}
class SubC extends SuperA
{
int C=15;
void AddAC()
{
AddA();
System.out.println("The Value of AddAC="+(A+C));
}
}
class HierarchialInheritance
{
public static void main(String args[])
{
SubB sob=new SubB(); //creating object for subclass SubB
System.out.println("Calling from Sub B");
sob.AddAB();
SubC soc=new SubC();//creating object for subclass SubC
System.out.println("Calling from Sub C");
soc.AddAC();
}
}
Program 5.4 Example for Hierarchical Inheritance
Output
I:\java\OOPS>javac HierarchialInheritance.java
I:\java\OOPS>java HierarchialInheritance
Calling from Sub B
Using Classes 5.7

The value of AddAB=15


Calling from Sub C
The value of AddA=10
The Value of AddAC=20

Multiple inheritances
In java multiple inheritances was not support. We can implement multiple
inheritance using interfaces. Interface is explained in the chapter 5.15.

5.7 Polymorphism

Polymorphism is the ability of an object to take more than one form

Two types of polymorphism

1) Compile time or earlier binding. Example overloading.


2) Run time or dynamic binding. Example overriding.

Compile time
Method overloading is the technique example for compile time polymorphism.

5.8 Method overloading


Methods have the same name, but different parameter lists with different data
types in parameter.

class methodoverload
{
void add(int a, int b)
{
int sum=a+b;
System.out.println("Sum of a+b is" +sum);
}
void add(int a, int b, int c)
{
int sum=a+b+c;
System.out.println("Sum of a+b+c is "+sum);
}
void add(String s1, String s2)
{
String s=s1+s2;
System.out.println(" Concatenation of string s1+s2 is" +s);
}
5.8 Java Programming Paradigms

void add(double a, double b)


{
double a+b;
system.out.println("The sum of double of (a+b) is" +sum);
}
}
class MethodOverloadMain
{
public static void main(String args[])
{
methodoverload mo=new methodoverload();
mo.add("java", "Programming");
mo.add(10,5);
mo.add(10,20,30);
mo.add(40.5,50.5);
}
}
Program 5.5 Example for Method Overloading
Output
E:\program\Polymorphism>javac MethodOverloadMain.java
E:\program\Polymorphism>java MethodOverloadMain
Concatenation of string s1+s2 isjavaProgramming
Sum of integer a+b is15
Sum of integer a+b+c is 60
Concatenation of string s1+s2 isjavaProgramming
The sum of double of (a+b) is91.0

When an object are required to perform the similar task on the same
method_name but using different parameter, then method overloading is used.
While calling a method through object, java matches up the method name first
and then the number and type of parameters, it will decide which one of the definitions to
be executed.
From the above code example we have add() as same method with different
parameter list and with different data types. If the parameter passed is matches then the
particular method will be called.

5.9 Constructor Overloading


A class which have any number of constructor which differs in parameter lists.
Where constructor name should same as method name.
The compiler differentiates these constructors by taking into account the number
of parameters in the list and their type.
Using Classes 5.9

class adds
{
void adds(int a, int b)
{
int sum=a+b;
System.out.println("Sum of integer a+b is " +sum);
}
void adds(double c, double d)
{
double sum=c+d;
System.out.println("Sum of double a+b is " +sum);
}
}
class ConstructorOverloading
{
public static void main(String args[])
{
adds a=new adds();
a.adds(10, 15);
a.adds(10.5, 15.5);
}
}
Program 5.6 Example for Constructor Overloading
Output
E:\program\Polymorphism>javac ConstructorOverloading.java
E:\program\Polymorphism>java ConstructorOverloading
Sum of integer a+b is 25
Sum of double a+b is 26.0

5.10 Dynamic Polymorphism (Runtime Polymorphism)


Run time polymorphism was achieved by method overriding.
Method overriding must have the same method name with same parameter list
and same data type. Method overriding is resolved at runtime instead of compile time.
Method overriding is the process of defining a method in the sub class which was already
defined in the superclass. Method overriding applies only to the inherited methods.
Overridden method will be executed in response to a method call at runtime.
class Superclasses
{
void add(int a, int b)
{
int sum=a+b;
5.10 Java Programming Paradigms

System.out.println("Sum of a+b in superclass is "+sum);


}
}
class Subclass extends Superclasses
{
void add(int a, int b)
{
int c=10;
int sum=a+b+c;
System.out.println("Sum of a+b+c in sub class is " +sum);
}
}
class DynamicPolymorphism1
{
public static void main(String args[])
{
Superclasses sup = new Superclasses();
sup.add(100,150);
Superclasses sub = new Subclass();
sub.add(10,15);
}
}
Program 5.7 Example for Method Overriding
Output:
I:\java\OOPS>javac DynamicPolymorphism1.java
I:\java\OOPS>java DynamicPolymorphism1
Sum of a+b in superclass is250
Sum of a+b+c in sub class is35

Rules for method overriding


 The argument list should be exactly the same as that of the overridden method.
 The return type should be the same or a subtype of the return type declared in the
original overridden method in the super class.
 The access level cannot be more restrictive than the overridden method's access
level. For example: if the super class method is declared public then the
overriding method in the sub class cannot be either private or protected.
 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.
Using Classes 5.11

 A subclass in a different package can only override the non-final methods


declared public or protected.
 Constructors cannot be overridden.

Using the super keyword


When invoking a superclass version of an overridden method the super keyword is used.
class Superclasses
{
void add(int a, int b)
{
int c=5;
int sum=a+b+c;
System.out.println("Sum of a+b+c in superclass is "+sum);
}
}
class Subclass extends Superclasses
{
void add(int a, int b)
{
int c=10;
int sum=a+b+c;
super.add(a,b); // super.add(a,b)represents the superclass method add
System.out.println("Sum of a+b+c in sub class is " +sum);
}
}
class DynamicPolymorphism
{
public static void main(String args[])
{
Subclass sub = new Subclass();
sub.add(10,15);
}
}
Program 5.8 Example for Method Overriding using super keyword
super has two general forms.
 super calls the superclass’s constructor.
 super is used to access a member of the superclass that has been hidden
by a subclass.
super.add(a,b); will get the superclass method add(int a, int b).
Output
I:\java\OOPS>javac DynamicPolymorphism.java
I:\java\OOPS>java DynamicPolymorphism
5.12 Java Programming Paradigms

Sum of a+b+c in superclass is 30


Sum of a+b+c in sub class is 35
In the above example, overriding method add(int a, int b) have the same name,
same parameter list, same datatype is used in superclass and subclass.

The object call super.add(10,10) will invoke the superclass method. When the
object call sub.add(10,15) will invoke the subclass method.

5.11 Packages

One of the main features of OOPS is code reusability. In java, inheritance and
interface are used for code reusability within a program. To use the code from one
program to other program the concept package will used.
In Java, package is a namespace that allows you to grouping of related types
(class, interfaces, enumerations and annotations ) providing access protection and name
space management.
If we want to access a package in a class, we should import the package in the
program. There are two types of packages.

1. System package/ Java API packages (Java Programming Language Application


Programming Interfaces).
2. User defined packages.

5.12 Java API packages


Java API provides a large number of classes grouped into different packages. They are

Package Description
Provides the classes necessary to create an applet and the classes an applet uses to
java.applet
communicate with its applet context.
Contains all of the classes for creating user interfaces and for painting graphics and
java.awt
images.
Provides for system input and output through data streams, serialization and the file
java.io
system.
Provides classes that are fundamental to the design of the Java programming
java.lang
language.
Provides classes for performing arbitrary-precision integer arithmetic (BigInteger)
java.math
and arbitrary-precision decimal arithmetic (BigDecimal).
java.net Provides the classes for implementing networking applications.
java.nio Defines buffers, which are containers for data, and provides an overview of the
Using Classes 5.13

other new IO packages.


java.rmi Provides the RMI package.
java.security Provides the classes and interfaces for the security framework.
Provides the API for accessing and processing data stored in a data source (usually
java.sql
a relational database) using the JavaTM programming language.
Provides classes and interfaces for handling text, dates, numbers, and messages in a
java.text
manner independent of natural languages.
Contains the collections framework, legacy collection classes, event model, date
java.util and time facilities, internationalization, and miscellaneous utility classes (a string
tokenizer, a random-number generator, and a bit array).
javax.swing
hierarchy of packages for platform-independent rich GUI components

Table 5.1 Java System Packages


java

awt Package containing


awt package
Color

Graphics
Package containing
classes
Font

Classes containing
Image
methods

Figure 5.3 Hierarchical representation of java.awt.package


5.14 Java Programming Paradigms

The system package can be accessed by the format


import packagename.*;

example
import java.io.*;

The above package includes all the classes in input/output.

import java.lang.math.*;

This include the classes ‘math’ from the package “lang”.

5.13 Naming convention


Package can be names using the standard java naming rules.Package begins with
the lowercase letter. This to distinguish between classes and package.
Double y=java.lan.Math.sqrt(x);

package class method


name name name
Here the package starts with lowercase. We know that all classname, begins with
an uppercase letter(Math) invoke method sqrt(x).
Consider another example
java.awt.Point pts[];
Point qualifies classname

5.14 Creating and importing a package


Creating a package
1. Declare the name of the package using the package keyword followed by
package_name.
Syntax:
package packagename;

2. Package name should be the first statement in a java source file (Except for
comments and white space) followed by class, interfaces, enumeration type that
you want to include in the package.
Example
package travelpackage;
class Passenger
{
…..
}
Using Classes 5.15

Make a directory name as travelpackage in E:\program as shown in given below picture.

Inside this package save the following file as Passenger.java as shown in given below
picture.

CODING of Passenger.java
package travelpackage;
public class Passenger
{
int noofPassenger;
int spare=20;
public Passenger(int x)
{
noofPassenger=x;
}
public int calculateAmount()
{
5.16 Java Programming Paradigms

return(spare*noofPassenger);
}}
To set path
set path="C:\Program Files\Java\jdk1.6.0_07\bin"
in the command prompt for the location E:\program\travelpackage.
Compile the file Passenger.java

To get the code to use in other program, you need to import the package.

Syntax:
import packagename.*;

Coding of travelAmount importing travelpackage.


import travelpackage.*;
class travelAmount
{
public static void main(String args[])
{
Passenger p1=new Passenger(40);
int amount=p1.calculateAmount();
System.out.println("Total amount for all passenger using package="+amount);
}
}
After creating the code, just save the above coding file outside the directory
travelpackage as travelAmount.java (i.e.) you have to save this file in E:\program as
shown in the given below picture.

To set path

set path="C:\Program Files\Java\jdk1.6.0_07\bin"


Using Classes 5.17

in the command prompt for the location E:\program and compile travelAmount.java run
this file, you will get the output as.

E:\>cd program
E:\program>cd travelpackage
E:\program\travelpackage>path.bat
E:\program\travelpackage>set path="C:\Program Files\Java\jdk1.6.0_07\bin"
E:\program\travelpackage>javac Passenger.java
E:\program\travelpackage>cd..
E:\program>path.bat
E:\program>set path="C:\Program Files\Java\jdk1.6.0_07\bin"
E:\program>javac travelAmount.java
E:\program>java travelAmount
Total amount for all passenger using package=800

5.15 Interface
5.15.1 Introduction
Process of inheriting more than one super class in a sub class is called multiple
inheritance. Java does not support multiple inheritance. Classes in java cannot have more
than one superclass.
Example:
class a extends b extends c
{
…………
}
The above format is not allowed in java. Here java provides alternative approach
known as interface, to support the concept of multiple inheritance.
Interface is a way of describing what classes should do, without specifying how
they should do it.
A class can implement one or more interface.

5.15.2 Defining an interface

In Java interface is declared like class which contain methods & variable. In
interface the methods are as abstract method and the fields are as final fields.

In interface, methods will not have the implementation coding, the methods
coding will be implemented in the sub classes.

In interface, fields are as final fields


5.18 Java Programming Paradigms

Syntax

interface interfaceName
{
// variable declaration;
// method declaration();
}
Interface should be declared by interface keyword followed by interfaceName.

Variables are declared as follow

static final type variableName=value;

All variables are declared as constant.

Methods are declared will not have implementation coding

returntype methodName(parameter_list);

5.15.3 Extending interface


Like classes, interface can also inherit another interface. So the interface can also
be extended using the keyword extends as shown below.
interface interfacename2 extends interfacename1
{
//Body of interfcaename2
}

5.15.4 Implementing interface


Interface is used as “superclasses” whose properties are inherited by classes. It is
therefore necessary to create a class that inherits the given interface. This is done as
follow.
class classname implements interface
{
Body of classname
}

The below syntax shows a class extends a superclass and implements an interface.

class classname extends superclass implements interfacename1, interfacename2,….


{
//Body of classname
}
Using Classes 5.19

The below diagram described for the above class extends and implements interface.

superclass interfacename1 interfacename2

class

Figure 5.4 Various forms of interface implementation (Shown Below)

class A interface A interface A


extends extends

class interface B implements


B
implementation class B class C

class C
interface interface
A B

extends

C interface

implements

D class

interface Father
{
double Salary = 10000;
void show();
}
5.20 Java Programming Paradigms

interface Mother
{
double Salary = 30000;
void show();
}
class MyClass implements Father, Mother
{
public void show()
{
System.out.println("Total family Salary of the month :"
+(Father.Salary+Mother.Salary));
}
}
class InterfaceDemo
{
public static void main(String args[])
{
MyClass ob1 = new MyClass();
ob1.show();
}
}
Program 5.9 Example for interface.
Output
I:\java\OOPS>javac InterfaceDemo.java

I:\java\OOPS>java InterfaceDemo
Total family Salary of the month :40000.0

interface Shape
{ void area ();
void volume ();
double pi = 3.14;
}
class Circle implements Shape {
double r;
Circle (double radius)
{
r = radius;
}
public void area ()
{
Using Classes 5.21

System.out.println ("Area of a circle is : " + pi*r*r );


}
public void volume ()
{
System.out.println ("Volume of a circle is : " + 2*pi*r);
}
}
class Rectangle implements Shape {
double l,b;
Rectangle (double length, double breadth)
{
l = length;
b = breadth;
}
public void area ()
{
System.out.println ("Area of a Rectangle is : " + l*b );
}
public void volume ()
{
System.out.println ("Volume of a Rectangle is : " + 2*(l+b));
}
}
class Interfaceshape {
public static void main (String args[])
{
Circle ob1 = new Circle (10.2);
ob1.area ();
ob1.volume ();
Rectangle ob2 = new Rectangle (12.6, 23.55);
ob2.area ();
ob2.volume ();
}
}
Program 5.10 Example for interface.
Output
I:\java\graphics>javac Interfaceshape.java
I:\java\graphics>java Interfaceshape
Area of a circle is : 326.68559999999997
Volume of a circle is : 64.056
Area of a Rectangle is : 296.73
Volume of a Rectangle is : 72.3
5.22 Java Programming Paradigms

5.16 Class Hierarchy


The collection of all classes extending from a common superclass is called an inheritance
hierarchy.
 The relationship between classes can be represented in a hierarchical view often called
class tree view.
 The path from a particular class to its family tree in the inheritance hierarchy is its
inheritance chain.

Principal

All HOD’s Manager

Teaching Staffs Lab Assistants Office Staffs


Figure 5.5 Example for class Hierarchy

Another example for class hierarchy


Object

Character
s

Digits Letters

Constant Vowels
s
Figure 5.6 Another Example for class Hierarchy

5.17 Abstract Class

 Classes from which objects cannot be instantiated with new operator are called
abstract classes.
 Each abstract class contains one or more abstract methods.
 In a abstract class, methods will not have implementation coding (i.e. method
body) is known as abstract method.
Using Classes 5.23

Abstract class declaration


Syntax:
abstract class classname{ …}
Example:
abstract class Shape
{
…………
…………
}
 Abstract keyword must be use infront of the class keyword at the beginning of the
class declaration.
 No objects are created to an abstract class.

Abstract Method
Syntax
abstract methodname(parameter list);
Example
abstract double area();

 ‘Abstract’ is a keyword used for declaring abstract method. And method should
be finished with semicolon. For the abstract methods, the implementation code
will be defined in its subclass.
 Note: we cannot declare any abstract construction.

Abstract Class Program


Write an abstract class program for the given below diagram to find their areas
respectively.
Shape

Rectangle Circle Triangle Ellipse Square

Figure 5.7 (A Class Hierarchy)


5.24 Java Programming Paradigms

abstract class Shape


{
double dim1;
double dim2;
double PI=3.14;
Shape(double a,double b)
{
dim1=a;
dim2=b;
}
abstract double area();
}
class Rectangle extends Shape
{
Rectangle(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside Area for Rectangle:");
return dim1*dim2;
}
}
class Triangle extends Shape
{
Triangle(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside Area for Triangle:");
return dim1*dim2/2;
}
}
class Circle extends Shape
{
Circle(double a,double b)
{
super(a,b);
}
Using Classes 5.25

double area()
{
System.out.println("Inside Area for circle:");
return PI*dim1*dim1;
}
}
class Ellipse extends Shape
{
Ellipse(double a,double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside Area for Ellipse:");
return PI * dim1 * dim2;
}
}
class Square extends Shape
{
Square(double a, double b)
{
super(a,b);
}
double area()
{
System.out.println("Inside Area for Square:");
return dim1 * dim1;
}
}
classAbstractAreas
{
public static void main (String args[])
{
Rectangle r=new Rectangle(9,5);
Triangle t=new Triangle(10,8);
Circle c=new Circle(5,5);
Ellipse e=new Ellipse(7,7);
Square s=new Square(6,6);
Shape figref;
figref=r;
System.out.println("Area is "+figref.area());
5.26 Java Programming Paradigms

figref=t;
System.out.println("Area is "+figref.area());
figref=c;
System.out.println("Area is "+figref.area());
figref=e;
System.out.println("Area is "+figref.area());
figref=s;
System.out.println("Area is "+figref.area());
}
}
Program 5.11 Example for Abstract Class
Output:

Inside Area for Rectangle:


Area is 45.0
Inside Area for Triangle:
Area is 40.0
Inside Area for circle:
Area is 78.5
Inside Area for Ellipse:
Area is 153.86
Inside Area for Square:
Area is 36.0
5.18 Final keyword
Final keyword is used for three purposes in java, they are
o Final variable
o Final method
o Final class
Final variable
Variables declaration with final keyword is constant. Once we assign the value for the
variable, the value can’t be changed.
Syntax
final datatypes variable_name=value;

Example
final int a=20;

here the value of a=20. If we change the value of a for example

a=24; //will show compile time error


if the variable ‘a’ is not initialized while declaring.
Using Classes 5.27

Example:
final int a;

after this statement you can assign any value to the variable, but only once.
Example
final int a;
a=20; //ok
a=23; //compile time error
Final method
A method that is declared as final, then the method cannot be overridden in a
subclass method. If you try to override the final method, it will show compiler error.
Syntax
final returntype methodname()
{
………
……….
}
Example
Class finalmethod
{
final void show()
{
System.out.pritnln(“This is final method in java”);
}
}
class subfinalmethod extends finalmethod
{
void show()
{
// show compiler error. The method show cannot be override the final method in subclass.
}
}

Final class
Class declared as final, then class be extended to the subclass. Inheritance is not
possible in final class.
Syntax:
final class classname()
{
……….
……….
}
5.28 Java Programming Paradigms

Example

final class fclass


{
void show()
{
System.out.println(“this is final class cannot be extended”);
}
}
class fmainclass extends fclass //shows compiler error
{
………….
………….
}
Note

Can abstract class and abstract method be final?


Abstract class and abstract method cannot be final because an abstract class needs to be
extended which will not possible if you declare as ‘final’.

What happens when I declare a method inside a class as both ‘private’ and ‘final’ ?
Making a class both ‘private’ and ‘final’ makes the ‘final’ keyword redundant as a private
method cannot be accessed in its sub class. But hey, you’ll be able to declare a method of
the same name as in the base class if the method has been made private in the base class.
But then that doesn’t mean you’re overriding the method. You’re simply declaring a new
method in the sub class.

5.19 Object Class

Object class is the root of the class hierarchy. The Object class is the ultimate
ancestor—every class in Java extends Object. However, you never have to write

class ObjectClass extends Object

The ultimate superclass Object is taken for granted if no superclass is explicitly


mentioned. Because every class in Java extends Object, it is important to be familiar with
the services provided by the Object class.

You can use a variable of type Object to refer to objects of any type:
Object obj = new ObjectClass("JAVA");
Using Classes 5.29

Of course, a variable of type Object is only useful as a generic holder for arbitrary
values. To do anything specific with the value, you need to have some knowledge about
the original type and then apply a cast:
ObjectClass e = (ObjectClass) obj;
In Java, only the primitive types (numbers, characters, and boolean values) are not
objects.
equals()
The equals method in the Object class tests whether one object is considered
equal to another. The equals method, as implemented in the Object class, determines
whether two object references are identical. If object reference are equal then return true,
otherwise false.
Example
if(oc1.equals(oc2))

getClass()
Returns the runtime class of an object. That Class object is the object that is
locked by static synchronized methods of the represented class.
Example
oc1.getClass();
hashCode()
A hash code is an integer that is derived from an object. Hash codes should be
climbed—if x and y are two distinct objects, there should be a high probability that
x.hashCode() and y.hashCode() are different integer result. If two objects are equal
according to the equals(Object) method, then calling the hashCode method on each of the
two objects must produce the same integer result.
Hashcode returns a hash code for this object. A hash code can be any integer,
positive or negative. Equal objects need to return identical hash codes.
Example
oc1.hashCode();
toString()
object toString() method returns a String representation of the object. You can use
toString to display an object.
Example
oc1.toString();
class ObjectClass
{
String a;
ObjectClass(String b)
{
a=b;
}
ObjectClass()
5.30 Java Programming Paradigms

{
}
void printString()
{
System.out.println("String ="+a);
}
}
class ObjectClassTest
{
public static void main(String args[])
{
ObjectClass oc1=new ObjectClass("JAVA");
oc1.printString();
ObjectClass oc2=new ObjectClass("DOTNET");
oc2.printString();
// check equal() method
if(oc1.equals(oc2))
System.out.println("Objects oc1 and oc2 are equal");
else
System.out.println("Objects oc1 and oc2 are not equal");
oc2=oc1;
if(oc1.equals(oc2))
System.out.println("Objects oc1 and oc2 are equal");
else
System.out.println("Objects oc1 and oc2 are not equal");
//To get tostring() method
System.out.println("The string value of the object oc1="+oc1.toString());
//To get hashcode() method
ObjectClass cl=new ObjectClass();
System.out.println("The hashcode for object cl="+cl.hashCode());
System.out.println("The hashcode for object oc1="+oc1.hashCode());
System.out.println("The hashcode for object oc2="+oc2.hashCode());
//To getclass of the object
System.out.println("The runtime class of an object oc1="+oc1.getClass());
}
}
Program 5.12 Example for Object Class
Output
E:\program>java ObjectClassTest
String =JAVA
String =DOTNET
Objects oc1 and oc2 are not equal
Using Classes 5.31

Objects oc1 and oc2 are equal


The string value of the object oc1=ObjectClass@19821f
The hashcode for object cl=11394033
The hashcode for object oc1=1671711
The hashcode for object oc2=1671711
The runtime class of an object oc1=class ObjectClass

5.20 Reflection

Reflection library gives you a very rich and elaborate tool set to write programs
that manipulate java code dynamically. Reflection has the ability to analyze the
capabilities of classes at runtime. It also allows you to analyze a software component and
describe its capabilities dynamically, at runtime rather than at compile time. For example
by using reflection, you can determine what methods, constructors and field a class
support.

The package java.lang.Reflection has an interface called member, which defines


methods that allow you to get information about a field, constructor (or) method of a
class. There are also eight classes in this package.

Consider the following class (java.awt.Dimension) in the (Program) to print


constructors, methods and fields. The program beings by using the forName() methods of
class to get a class object for java.awt.Dimension. Once this is obtained, getConsturtors(),
getFields() and getMethods() are used to analyze this class object and the (constructors,
fields and methods) will be show.

They return arrays of constructor, fields and methods objects that provide the
information about the object. The constructor, field and method classes define several
methods that can be used to obtain information about an object.

Using Java Reflection you can inspect Java classes at runtime. Inspecting classes is
often the first thing you do when using Reflection. From the classes you can obtain
information about
 Class Name
 Class Modifies (public, private, synchronized etc.)
 Package Info
 Superclass
 Implemented Interfaces
 Constructors
 Methods
5.32 Java Programming Paradigms

 Fields
 Annotations
plus a lot more information related to Java classes. For a full list you should consult
the JavaDoc for java.lang.Class. This text will briefly touch upon all accessing of the
above mentioned information. Some of the topics will also be examined in greater detail
in separate texts. For instance, this text will show you how to obtain all methods or a
specific method, but a separate text will show you how to invoke that method, how to
find the method matching a given set of arguments if more than one method exists with
the same name, what exceptions are thrown from method invocation via reflection, how
to spot a getter/setter etc. The purpose of this text is primarily to introduce the Class
object and the information you can obtain from it.

The Class Object


Before you can do any inspection on a class you need to obtain its
java.lang.Class object. All types in Java including the primitive types (int, long, float
etc.) including arrays have an associated Class object. If you know the name of the class
at compile time you can obtain a Class object like this:
Class myObjectClass = MyObject.class

If you don't know the name at compile time, but have the class name as a string at
runtime, you can do like this:
String className = ... //obtain class name as string at runtime
Class class = Class.forName(className);

When using the Class.forName() method you must supply the fully qualified
class name. That is the class name including all package names. For instance, if
MyObject is located in package com.jenkov.myapp then the fully qualified class name is
com.jenkov.myapp.MyObject
The Class.forName() method may throw a ClassNotFoundException if the class
cannot be found on the classpath at runtime.

Class Name
From a Class object you can obtain its name in two versions. The fully qualified
class name (including package name) is obtained using the getName() method like this:
Class aClass = ... //obtain Class object. See prev. section
String className = aClass.getName();

If you want the class name without the pacakge name you can obtain it using the
getSimpleName() method, like this:
Class aClass = ... //obtain Class object. See prev. section
String simpleClassName = aClass.getSimpleName();
Using Classes 5.33

Modifiers
You can access the modifiers of a class via the Class object. The class modifiers
are the keywords "public", "private", "static" etc. You obtain the class modifiers like this:
Class aClass = ... //obtain Class object. See prev. section
int modifiers = aClass.getModifiers();

The modifiers are packed into an int where each modifier is a flag bit that is
either set or cleared. You can check the modifiers using these methods in the class
java.lang.reflect.Modifier:
Modifier.isAbstract(int modifiers)
Modifier.isFinal(int modifiers)
Modifier.isInterface(int modifiers)
Modifier.isNative(int modifiers)
Modifier.isPrivate(int modifiers)
Modifier.isProtected(int modifiers)
Modifier.isPublic(int modifiers)
Modifier.isStatic(int modifiers)
Modifier.isStrict(int modifiers)
Modifier.isSynchronized(int modifiers)
Modifier.isTransient(int modifiers)
Modifier.isVolatile(int modifiers)

Package Info
You can obtain information about the package from a Class object like this:
Class aClass = ... //obtain Class object. See prev. section
Package package = aClass.getPackage();
From the Package object you have access to information about the package like
its name. You can also access information specified for this package in the Manifest file
of the JAR file this package is located in on the classpath. For instance, you can specify
package version numbers in the Manifest file. You can read more about the Package
class here: java.lang.Package
Superclass
From the Class object you can access the superclass of the class. Here is how:
Class superclass = aClass.getSuperclass();

The superclass class object is a Class object like any other, so you can continue
doing class reflection on that too.

Implemented Interfaces
It is possible to get a list of the interfaces implemented by a given class. Here is
how:
5.34 Java Programming Paradigms

Class aClass = ... //obtain Class object. See prev. section


Class[] interfaces = aClass.getInterfaces();

A class can implement many interfaces. Therefore an array of Class is returned.


Interfaces are also represented by Class objects in Java Reflection.

NOTE: Only the interfaces specifically declared implemented by a given class is


returned. If a superclass of the class implements an interface, but the class doesn't
specifically state that it also implements that interface, that interface will not be returned
in the array. Even if the class in practice implements that interface, because the superclass
does.
To get a complete list of the interfaces implemented by a given class you will have to
consult both the class and its superclasses recursively.

Constructors
You can access the constructors of a class like this:
Constructor[] constructors = aClass.getConstructors();
Constructors are covered in more detail in the text on Constructors.

Methods
You can access the methods of a class like this:
Method[] method = aClass.getMethods();
Methods are covered in more detail in the text on Methods.

Fields
You can access the fields (member variables) of a class like this:
Field[] method = aClass.getFields();
Fields are covered in more detail in the text on Fields.

Annotations
You can access the class annotations of a class like this:
Annotation[] annotations = aClass.getAnnotations();
Annotations are covered in more detail in the text on Annotations.

Java Reflection: Constructors


Using Java Reflection you can inspect the constructors of classes and instantiate
objects at runtime. This is done via the Java class java.lang.reflect.Constructor.
This text will get into more detail about the Java Construcor object. Here is a list of the
topics covered:
1. Obtaining Constructor Objects
2. Constructor Parameters
3. Instantiating Objects using Constructor Object
Using Classes 5.35

Obtaining Constructor Objects


The Constructor class is obtained from the Class object. Here is an example:
Class aClass = ...//obtain class object
Constructor[] constructors = aClass.getConstructors();
The Constructor[] array will have one Constructor instance for each public
constructor declared in the class.
If you know the precise parameter types of the constructor you want to access, you can
do so rather than obtain the array all constructors. This example returns the public
constructor of the given class which takes a String as parameter:
Class aClass = ...//obtain class object
Constructor constructor =
aClass.getConstructor(new Class[]{String.class});
If no constructor matches the given constructor arguments, in this case String.class, a
NoSuchMethodException is thrown.

Constructor Parameters
You can read what parameters a given constructor takes like this:
Constructor constructor = ... // obtain constructor - see above
Class[] parameterTypes = constructor.getParameterTypes();

Instantiating Objects using Constructor Object


You can instantiate an object like this:
//get constructor that takes a String as argument
Constructor constructor = MyObject.class.getConstructor(String.class);

MyObject myObject = (MyObject)


constructor.newInstance("constructor-arg1");

The Constructor.newInstance() method takes an optional amount of


parameters, but you must supply exactly one parameter per argument in the constructor
you are invoking. In this case it was a constructor taking a String, so one String must
be supplied.
Using constructor, field, and method objects as argument s to the println() method
as show below.
import java.lang.reflect.*;
public class ReflectionDemo1
{
public static void main(String args[])
{
try
{
5.36 Java Programming Paradigms

Class c = Class.forName("java.awt.Dimension");
System.out.println("Constructors:");
Constructor constructors[] = c.getConstructors();
for(int i = 0; i < constructors.length; i++)
{
System.out.println(" " + constructors[i]);
}
System.out.println("Fields:");
Field fields[] = c.getFields();
for(int i = 0; i < fields.length; i++)
{
System.out.println(" " + fields[i]);
}
System.out.println("Methods:");
Method methods[] = c.getMethods();
for(int i = 0; i < methods.length; i++)
{
System.out.println(" " + methods[i]);
}
}
catch(Exception e)
{
System.out.println("Exception: " + e);
}
}
}
Program 5.13 Example for Reflection
OUTPUT
Constructors:
public java.awt.Dimension()
public java.awt.Dimension(int, int)
public java.awt.Dimension(java.awt.Dimension)
Fields:
public static final long java.io.Serializable.serialVersionUID
public int java.awt.Dimension.width
public int java.awt.Dimension.height
Methods:
public java.lang.Object java.awt.geom.Dimension2D.clone( )
public boolean java.awt.Dimension.equals(java.lang.Object)
public final native java.lang.Class java.lang.Object.getClass( )
public native int java.lang.Object.hashCode( ) public final
native void java.lang.Object.notify( ) public final native void
Using Classes 5.37

java.lang.Object.notifyAll( ) public java.lang.String


java.awt.Dimension.toString( ) public final void
java.lang.Object.wait( )
throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long)
throws java.lang.InterruptedException
public final native void java.lang.Object.wait(long, int)
throws java.lang.InterruptedException public
double java.awt.Dimension getHeight( ) public
double java.awt.Dimension getWidth( )
public void java.awt.Dimension.setSize(double, double)
public void java.awt.geom.Dimension2D.setSize
(java.awt.geom.Dimension2D)
public java.awt.Dimension java.awt.Dimension.getSize( )
public void java.awt.Dimension.setSize(int, int)
public void java.awt.Dimension.setSize(java.awt.Dimension)

5.21 Inner classes


Defining a class within another class; such a class is called as nested class. Inner
class is member of its enclosing class. (Here enclosing class refer to code between {&}
open bracket and close bracket.

Example
Class outerclass
{
…….
class NestedClass
{
………
}
}
If class B is defined within class A, then B is known to A, but not outside of A. A
nested class has access to the members, including private members, of the class in which
it is nested.

Nested class is classified into two types


Static: nested classes that are declared static are simply called static nested class.
Non static: Non Static Classes are called inner class.
Static Nested Class

A static nested class must access the members of its enclosing class through an
object. It cannot refer to members of its enclosing class directly.
5.38 Java Programming Paradigms

class OuterClass
{
...
static class StaticNestedClass
{
...
}
class InnerClass
{
...
}
}

Non Static Nested Class


It can access all variables and methods of its outer class and may refer to them
directly to the outer class.
class Outer
{
String outstr="outerclass";
void check()
{
Inner in =new Inner();
in.show();
}
// Inner Class
class Inner
{
String instr="innerclass";
void show()
{
System.out.println("String of outerclass="+outstr);//variable outstr is accessed directly
System.out.println("String of inner class="+instr);
}
}
}
class SampleInnerClass
{
public static void main(String args[])
{
Outer out = new Outer();
out.check();
}
}
Program 5.14 Example program for inner class
Using Classes 5.39

Output
E:\program>javac SampleInnerClass.java
E:\program>java SampleInnerClass
String of outer class=outerclass
String of inner class=innerclass
In the above example Inner class is defined within the scope of the class Outer. So
the variable ‘outstr’ can be directly access by the class Inner. Method show() in Inner
class display (the both variable of Outer class (outstr) and Inner class (instr). Object out is
created for the class Outer in the main method of SampleInnerClass and invokes check()
method. The method check() creates an instance of class Inner and the show() method is
called.
If the Inner class is outside the scope of the Outer class then java compiler will generates
an error message.

 The ways to access the inner class is through its outer class only.
 An object to inner class can be created only in its outer class.
 An object to inner class cannot be created in any other class.
 Outer class members are available to inner class.
Review Questions
Part-A
1) Why is multiple inheritance using classes a disadvantage in java?
2) How to define an interface?
3) Explain the different forms of Polymorphism.
4) What is Dynamic Binding?
5) What is super?
6) What are the differences between Interface and Abstract class?
7) How are this() and super() used with constructors?
8) What is final modifier?
9) Define class hierarchy.
10) Define interface.
11) Distinguish between inheritance and polymorphism.
12) Difference between method overloading and overriding methods.
13) What is the difference between an Interface and an Abstract class?
14) What is called abstract class?
15) Can abstract class and abstract method be final?
16) Define static inner classes.
17) State the difference between inner class and anonymous class.
18) What are the different types of object class methods available?
19) Define object classes.
20) Define reflection.
5.40 Java Programming Paradigms

Part-B
1) Define inheritance and explain the different types of inheritance.
2) Explain polymorphism with example program.
3) Explain dynamic binding with example program.
4) Describe the abstract classes with example program.
5) Where do you apply final keyword? Explain it in detail.
6) Explain how to create a package and how it can be accessed in other program
with example program.
7) Explain object classes with example program.
8) Describe briefly about interface in detail with example program.

You might also like