Unit 2 Reading Material
Unit 2 Reading Material
Unit – II
Inheritance and Polymorphism
Inheritance in java
Super and sub class
Overriding
Object class
Polymorphism
Dynamic binding
Generic programming
Casting objects
Instance of operator
Abstract class
Interface in java
Package in java
UTIL package.
Inheritance in java:
• Inheritance enables you to define a general class (i.e., a superclass) and later extend
it to more specialized classes (i.e., subclasses).
• Consider geometric objects. It is to design the classes to model geometric objects such
as circles and rectangles.
• Geometric objects have many common properties and behaviors. They can be drawn
in a certain color and be filled or unfilled.
• A general class GeometricObject can be used to model all geometric objects. This
class contains the properties color and filled and their appropriate getter and setter
methods.
• Contains the dateCreated property
• and the getDateCreated() and toString() methods.
• The toString() method returns a string representation of the object.
• Since a circle is a special type of geometric object, it shares common properties and
methods with other geometric objects.
• It makes sense to define the Circle class that extends the GeometricObject class.
• Likewise, Rectangle can also be defined as a subclass of GeometricObject.
[Link] = color;
[Link] = filled;
}
/** Return color */
public String getColor() {
return color;
}
/** Set a new color */
public void setColor(String color) {
[Link] = color;
}
/** Return filled. Since filled is boolean, its getter method is named isFilled */
public boolean isFilled() {
return filled;
}
[Link] = radius;
setColor(color);
setFilled(filled);
}
/** Return radius */
[Link] = radius;
}
/** Return area */
public double getArea() {
return radius * radius * [Link];
}
/** Return diameter */
public double getDiameter() {
return 2 * radius;
}
/** Return perimeter */
public double getPerimeter() {
return 2 * radius * [Link];
}
public RectangleFromSimpleGeometricObject() {
}
public RectangleFromSimpleGeometricObject(
double width, double height) {
[Link] = width;
[Link] = height;
}
public RectangleFromSimpleGeometricObject(double width, double height, String
color, boolean filled) {
[Link] = width;
[Link] = height;
setColor(color);
setFilled(filled);
}
/** Return width */
public double getWidth() {
return width;
}
• The keyword super refers to the superclass and can be used to invoke the superclass’s
methods and constructors.
• A subclass inherits accessible data fields and methods from its superclass
• The keyword super refers to the superclass of the class in which super appears. It can
be used in two ways:
■ To call a superclass constructor.
■ To call a superclass method.
• The keyword super refers to the superclass and can be used to invoke the
superclass’s methods and constructors.
• In any case, constructing an instance of a class invokes the constructors of all the
super classes along the inheritance chain.
• When constructing an object of a subclass, the subclass constructor first invokes its
superclass constructor before performing its own tasks.
• If the superclass is derived from another class, the superclass constructor invokes its
parent-class constructor before performing its own tasks.
• This process continues until the last constructor along the inheritance hierarchy is
called. This is called constructor chaining.
• Consider the following code:
public class Faculty extends Employee {
public static void main(String[] args) {
new Faculty();
}
public Faculty() {
[Link]("(4) Performs Faculty's tasks");
}
}
class Employee extends Person {
public Employee() {
this("(2) Invoke Employee's overloaded constructor");
[Link]("(3) Performs Employee's tasks ");
}
public Employee(String s) {
[Link](s);
}
}
class Person {
public Person() {
• The keyword super can also be used to reference a method other than the
constructor in the superclass.
• The syntax is:
– [Link](parameters);
• In the earlier example it can rewritten the printCircle() method in the Circle class as
follows:
public void printCircle() {
[Link]("The circle is created " + [Link]() + " and the radius is " +
radius);
}
• It is not necessary to put super before getDateCreated() in this case, however,
because getDateCreated is a method in the GeometricObject class and is inherited
by the Circle class.
Nevertheless, in some cases, as shown in the next section, the keyword super is needed
--------------------------------------------------------------------------------------------------
Overriding Methods :
• To override a method, the method must be defined in the subclass using the same
signature and the same return type as in its superclass.
• A subclass inherits methods from a superclass. Sometimes it is necessary for the
subclass to modify the implementation of a method defined in the superclass. This is
referred to as method overriding.
• For Example :
– The toString method in the GeometricObject class returns the string
representation of a geometric object. This method can be overridden to
return the string representation of a circle. To override it, add the following
new method in the Circle class
public class CircleFromSimpleGeometricObject extends
SimpleGeometricObject {
// Other methods are omitted
// Override the toString method defined in the superclass
public String toString() {
return [Link]() + "\nradius is " + radius;
}
}
• Overloading means to define multiple methods with the same name but different
signatures.
• Overriding means to provide a new implementation for a method in the subclass
• For example, the following two class definitions are the same:
}
-------------------------------------------------------------------------------------------------------------------
Polymorphism :
• A class defines a type. A type defined by a subclass is called a subtype, and a type
defined by its superclass is called a supertype
• For Example:
– Circle is a subtype of GeometricObject and GeometricObject is a supertype
for Circle.
public class PolymorphismDemo {
public static void main(String[] args) {
// Display circle and rectangle properties
}
• Output:
Created on Mon Mar 09 19:25:20 EDT 2011. Color is red
• An object of a subclass can be used wherever its superclass object is used. This is
commonly known as polymorphism (from a Greek word meaning “many forms”).
}
-------------------------------------------------------------------------------------------------------------------------
Dynamic binding :
• A method can be implemented in several classes along the inheritance chain. The
JVM decides which method is invoked at runtime.
• A method can be defined in a superclass and overridden in its subclass.
• For example, the toString() method is defined in the Object class and overridden in
GeometricObject.
• Consider the following code:
Object o = new GeometricObject();
[Link]([Link]());
• That is, Cn is the most general class, and C1 is the most specific class.
• In Java, Cn is the Object class. If o invokes a method p, the JVM searches for the
implementation of the method p in C1, C2, . . . , Cn-1, and Cn, in this order, until it is
found. Once an implementation is found, the search stops and the first-found
implementation is invoked.
}
Output:
Student
Student
Person
[Link]@130c19b
-------------------------------------------------------------------------------------------------------------------
Generic programming :
• Introduction : Generics enable you to detect errors at compile time rather than at
runtime
• Generic class or method permits you to specify allowable types of objects that the
class or method can work with. On attempting to use an incompatible object, the
compiler will detect that error.
• Motivations and Benefits : The motivation for using Java generics is to detect errors
at compile time.
• Java has allowed you to define generic classes, interfaces, and methods since JDK
1.5. Several interfaces and classes in the Java API were modified using generics.
• For example, prior to JDK 1.5 the [Link] interface was defined as
shown in Figure a, but since JDK 1.5 it is modified as shown in Figure b
•
• Here, <T> represents a formal generic type, which can be replaced later with an
actual concrete type. Replacing a generic type is called a generic instantiation.
• For example :
– An ArrayList and assigns its reference to variable cities.
ArrayList<String> cities = new ArrayList<String>();
– The following statement creates an ArrayList and assigns its reference to
variable dates. This ArrayList object can be used to store dates.
ArrayList<[Link]> dates = new ArrayList<[Link]> ();
import [Link];
public class TestArrayList {
[Link]("Tokyo");
// Contains [London, Denver, Paris, Miami, Seoul, Tokyo
[Link]("List size? " + [Link]());
[Link]("Is Miami in the list? " + [Link]("Miami"));
[Link]("The location of Denver in the list? "+
[Link]("Denver"));
[Link]("Is the list empty? " + [Link]()); // Print false
[Link]([Link]());
Display the contents in the list in reverse order
for (int i = [Link]() - 1; i >= 0; i––)
[Link]([Link](i) + " ");
[Link]();
// Create a list to store two circles
ArrayList<CircleFromSimpleGeometricObject> list = new ArrayList<>();
// Add two circles
[Link](new CircleFromSimpleGeometricObject(2));
[Link](new CircleFromSimpleGeometricObject(3));
// Display the area of the first circle in the list
[Link]("The area of the circle? " + [Link](0).getArea());
}
}
public static <E> void print(E[] list) {
for (int i = 0; i < [Link]; i++)
[Link](list[i] + " ");
[Link]();
}
}
• To invoke a generic method, prefix the method name with the actual type in angle
brackets.
• For example,
– GenericMethodDemo.<Integer>print(integers);
– GenericMethodDemo.<String>print(strings);
• Or Simple as follows:
– print(integers);
– print(strings);
-------------------------------------------------------------------------------------------------------------
Casting objects :
• One object reference can be typecast into another object reference. This is called
casting object.
• Two Types
– Implicit Casting
– Explicit casting
• Implicit Casting :
– The statement m(new Student()); assigns the object new Student() to a
parameter of the Object type.
– It is equivalent to
Object o = new Student(); // Implicit casting
m(o);
instanceof operator : is used to test whether the object is an instance of the specified type
(class or subclass or interface).
Object myObject = new Circle();
... // Some lines of code
/** Perform casting if myObject is an instance of Circle */
• The variable myObject is declared Object. The declared type decides which method
to match at compile time.
• Using [Link]() would cause a compile error, because the Object class
does not have the getDiameter method.
• The compiler cannot find a match for [Link](). Therefore, it is
necessary to cast myObject into the Circle type to tell the compiler that myObject is
also an instance of Circle.
}
Output :
The circle area is 3.141592653589793
The circle diameter is 2.0
The rectangle area is 1.0
---------------------------------------------------------------------------------------------
Abstract class
• Introduction : An abstract class cannot be used to create objects. An abstract class
can contain abstract methods, which are implemented in concrete subclasses.
• In the inheritance hierarchy, classes become more specific and concrete with each
new subclass.
• Moving from a subclass back up to a superclass, the classes become more general
and less specific.
• Class design should ensure that a superclass contains common features of its
subclasses.
• Sometimes a superclass is so abstract that it cannot be used to create any specific
instances. Such a class is referred to as an abstract class.
Abstract class .. [Link]
return color;
}
public void setColor(String color) {
[Link] = color;
}
[Link] = filled;
}
public [Link] getDateCreated() {
return dateCreated;
}
@Override
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +" and filled: " +
filled;
}
public abstract double getArea();
public abstract double getPerimeter();
}
• Abstract classes are like regular classes, instances of abstract classes cannot be
created using the new operator.
• An abstract method is defined without implementation. Its implementation is
provided by the subclasses.
• A class that contains abstract methods must be defined as abstract.
• The constructor in the abstract class is defined as protected, because it is used only
by subclasses. When an instance is created for a concrete subclass, its superclass’s
constructor is invoked to initialize data fields defined in the superclass.
Abstract class .. [Link] .. [Link] :
displayGeometricObject(geoObject2);
}
/** A method for comparing the areas of two geometric objects */
public static boolean equalArea(GeometricObject object1,GeometricObject object2)
{
return [Link]() == [Link]();
}
/** A method for displaying a geometric object */
Output:
The two objects have the same area? false
The area is 78.53981633974483
Example :
public interface Edible {
/** Describe how to eat */
public abstract String howToEat();
}
Interface in java .. [Link]
Notation:
The interface name and the method names are italicized.
The dashed lines and hollow triangles are used to point to the interface.
@Override
public String sound() {
return "Tiger: RROOAARR";
}
}
}
class Orange extends Fruit {
@Override
public String howToEat() {
return "Orange: Make orange juice";
Tiger: RROOAARR
Chicken: Fry it
Chicken: cock-a-doodle-doo
----------------------------------------------------------------------------------------------------------
Packages in Java
• Purpose of package : The purpose of package concept is to provide common classes
and interfaces for any program separately
• Packages in Java are the way to organize files when a project has many modules
Advantage of packages :
• Package is used to categorize the classes and interfaces so that they can be easily
maintained
• Application development time is less, because reuse the code
Types of package :
• Classified as two types:
– Predefined or built-in package
– User defined package
• "-d" is a specific tool which is tell to java compiler create a separate folder for the
given package in given path.
• When specific path is given then it creates a new folder at that location and when .
(dot) is used, it crates a folder at current working directory.
Any package program can be compiled but can neither be executed nor run. These
programs can be executed through user defined program which are importing package
program
Example :
Package program which is save with [Link] and compile by javac -d . [Link]
package mypack;
public class A
{
[Link]();
[Link]("show() class A");
}
}
first we create Package program which is save with [Link] and compiled by "javac -d .
[Link]". Again we import class "A" in class Hello using "import mypack.A;" statement.
Difference between Inheritance and package :
• Package concept is to reuse the feature both within the program and across the
programs between
- class to class,
- interface to interface
- interface to class
• Package keyword is always used for creating the undefined package and placing
common classes and interfaces.
• import is a keyword which is used for referring or using the classes and interfaces of
a specific package.
-----------------------------------------------------------------------------------------------------------------------
UTIL package :
• Java depends directly on several of the classes in this package, and many programs
will find these classes indispensable.
– The EventObject class and the EventListener interface, which form the basis
of the new AWT event model in Java 1.1.
– The Locale class in Java 1.1, which represents a particular locale for
internationalization purposes.
– The Calendar and TimeZone classes in Java. These classes interpret the value
of a Date object in the context of a particular calendar system.
– The ResourceBundle class and its subclasses, ListResourceBundle and
PropertyResourceBundle, which represent sets of localized data in Java 1.1
-----------------------------------------End of Unit2-------------------------------------------------