Chapter 5
Chapter 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.
Defining a Subclass
Syntax
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
class Super
{
----- Super
-----
}
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
Syntax
class Super
{
-----
----- Super
}
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
SuperA
AddA()
SubB SubC
AddAB() AddAC()
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
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
Compile time
Method overloading is the technique example for compile time polymorphism.
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
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.
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
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.
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
Graphics
Package containing
classes
Font
Classes containing
Image
methods
example
import java.io.*;
import java.lang.math.*;
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
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.*;
To set path
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.
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.
Syntax
interface interfaceName
{
// variable declaration;
// method declaration();
}
Interface should be declared by interface keyword followed by interfaceName.
returntype methodName(parameter_list);
The below syntax shows a class extends a superclass and implements an interface.
The below diagram described for the above class extends and implements interface.
class
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
Principal
Character
s
Digits Letters
Constant Vowels
s
Figure 5.6 Another Example for class Hierarchy
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 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.
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:
Example
final int a=20;
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
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.
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
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
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.
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.
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
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.
Constructor Parameters
You can read what parameters a given constructor takes like this:
Constructor constructor = ... // obtain constructor - see above
Class[] parameterTypes = constructor.getParameterTypes();
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
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.
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
{
...
}
}
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.