0% found this document useful (0 votes)
4 views35 pages

Unit 2 Reading Material

The document covers key concepts of Object-Oriented Programming (OOP) in Java, focusing on inheritance and polymorphism. It explains the relationship between superclasses and subclasses, the use of the 'super' keyword, method overriding, and the significance of polymorphism and dynamic binding. Additionally, it provides code examples to illustrate these concepts, including the implementation of geometric shapes like circles and rectangles.
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)
4 views35 pages

Unit 2 Reading Material

The document covers key concepts of Object-Oriented Programming (OOP) in Java, focusing on inheritance and polymorphism. It explains the relationship between superclasses and subclasses, the use of the 'super' keyword, method overriding, and the significance of polymorphism and dynamic binding. Additionally, it provides code examples to illustrate these concepts, including the implementation of geometric shapes like circles and rectangles.
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

Object Oriented Programming through JAVA

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:

• Introduction : Object-oriented programming allows you to define new classes from


existing [Link] is called inheritance.
• Software design using the object-oriented paradigm focuses on objects and operations
on objects.
• The object oriented approach combines the power of the procedural paradigm with an
added dimension that integrates data with operations into objects.
• Inheritance is an important and powerful feature for reusing software.
• Suppose it may require to define classes to model circles, rectangles, and triangles.
– These classes have many common features.
What is the best way to design these classes so as to avoid redundancy and make the system
easy to comprehend and easy to maintain? The answer is to use inheritance :

Super and sub class :

• 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.

The GeometricObject class is the superclass for Circle and Rectangle.

Super and sub class - [Link] :

public class SimpleGeometricObject {

private String color = "white";


private boolean filled;
private [Link] dateCreated;
/** Construct a default geometric object */
public SimpleGeometricObject() {

dateCreated = new [Link]();


}
/** Construct a geometric object with the specified color * and filled value */
public SimpleGeometricObject(String color, boolean filled) {
dateCreated = new [Link]();

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

/** Set a new filled */


public void setFilled(boolean filled) {
[Link] = filled;
}
/** Get dateCreated */

public [Link] getDateCreated() {


return dateCreated;
}
/** Return a string representation of this object */
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +" and filled: " + filled;
}
}
Super and sub class -- [Link] :

public class CircleFromSimpleGeometricObject extends SimpleGeometricObject{


private double radius;
public CircleFromSimpleGeometricObject() {
}

public CircleFromSimpleGeometricObject(double radius) {


[Link] = radius;
}
public CircleFromSimpleGeometricObject(double radius,
String color, boolean filled) {

[Link] = radius;
setColor(color);
setFilled(filled);
}
/** Return radius */

public double getRadius() {


return radius;
}
/** Set a new radius */
public void setRadius(double 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];
}

/** Print the circle info */


public void printCircle() {
[Link]("The circle is created " + getDateCreated() +" and the
radius is " + radius);
}
}

Super and sub class .. [Link] :

public class RectangleFromSimpleGeometricObject extends SimpleGeometricObject {


private double width;
private double height;

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

Super and sub class .. [Link] :


/** Set a new width */
public void setWidth(double width) {
[Link] = width;
}

/** Return height */


public double getHeight() {
return height;
}
/** Set a new height */

public void setHeight(double height) {


[Link] = height;
}
/** Return area */
public double getArea() {

return width * height;


}
/** Return perimeter */
public double getPerimeter() {
return 2 * (width + height);
}
}

Super and sub class .. [Link]

public class TestCircleRectangle {


public static void main(String[] args) {
CircleFromSimpleGeometricObject circle = new
CircleFromSimpleGeometricObject(1);
[Link]("A circle " + [Link]());
[Link]("The color is " + [Link]());
[Link]("The radius is " + [Link]());

[Link]("The area is " + [Link]());


[Link]("The diameter is " + [Link]());
RectangleFromSimpleGeometricObject rectangle = new
RectangleFromSimpleGeometricObject(2, 4);
[Link]("\nA rectangle " + [Link]());
[Link]("The area is " + [Link]());

[Link]("The perimeter is " + [Link]());


}
}
Output :
A circle created on Thu Feb 10 19:54:25 EST 2011
color: white and filled: false
The color is white
The radius is 1.0
The area is 3.141592653589793
The diameter is 2.0
A rectangle created on Thu Feb 10 19:54:25 EST 2011
color: white and filled: false
The area is 8.0
The perimeter is 12.0
---------------------------------------------------------------------------------------------------------------
Using the super Keyword :

• 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.

Using the super Keyword - Calling Superclass Constructors :

• The keyword super refers to the superclass and can be used to invoke the
superclass’s methods and constructors.

• A constructor is used to construct an instance of a class.


• Unlike properties and methods, the constructors of a superclass are not inherited by
a subclass.
• They can only be invoked from the constructors of the subclasses using the keyword
super.
• The syntax to call a superclass’s constructor is:
– super(), or super(parameters);
• The statement super() invokes the no-arg constructor of its superclass, and the
statement super(arguments) invokes the superclass constructor that matches the
arguments.
• The statement super() or super(arguments) must be the first statement of the
subclass’s constructor ,this is the only way to explicitly invoke a superclass
constructor
• For example,
• The constructor can be replaced by the following code:

public CircleFromSimpleGeometricObject(double radius, String color, boolean filled) {


super(color, filled);
[Link] = radius;
}
Using the super Keyword --Constructor Chaining :
• A constructor may invoke an overloaded constructor or its superclass constructor. If
neither is invoked explicitly, the compiler automatically puts super() as the first
statement in the constructor.
• For example:

• 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() {

[Link]("(1) Performs Person's tasks");


}
}

Using the super Keyword -- Calling Superclass Methods :

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

• An instance method can be overridden only if it is accessible. Thus a private method


cannot be overridden, because it is not accessible outside its own class.
• If a method defined in a subclass is private in its superclass, the two methods are
completely unrelated.
• Like an instance method, a static method can be inherited. However, a static method
cannot be overridden.
• If a static method defined in the superclass is redefined in a subclass, the method
defined in the superclass is hidden. The hidden static methods can be invoked using
the syntax [Link].
Overriding vs. Overloading ..

• 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

• Overridden methods are in different classes related by inheritance; overloaded


methods can be either in the same class or different classes related by inheritance.
• Overridden methods have the same signature and return type; overloaded methods
have the same name but a different parameter list.
The Object Class and Its toString() Method :
• Every class in Java is descended from the [Link] class

• If no inheritance is specified when a class is defined, the superclass of the class is


Object by default.

• For example, the following two class definitions are the same:

• The signature of the toString() method is:


– public String toString()
• Invoking toString() on an object returns a string that describes the object.
The Object Class and Its toString() Method :
• The signature of the toString() method is:

– public String toString()


• Invoking toString() on an object returns a string that describes the object.
• For example, the toString method in the Object class was overridden in the
GeometricObject class as follows:
public String toString() {
return "created on " + dateCreated + "\ncolor: " + color +
" and filled: " + filled;

}
-------------------------------------------------------------------------------------------------------------------
Polymorphism :

• Polymorphism means that a variable of a supertype can refer to a subtype object

• 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

displayObject(new CircleFromSimpleGeometricObject (1, "red", false));


displayObject(new RectangleFromSimpleGeometricObject (1, 1, "black", true));
}
/** Display geometric object properties */
public static void displayObject(SimpleGeometricObject object) {

[Link]("Created on " + [Link]() +". Color is " +


[Link]());

}
• Output:
Created on Mon Mar 09 19:25:20 EDT 2011. Color is red

Created on Mon Mar 09 19:25:20 EDT 2011. Color is black


• The method displayObject takes a parameter of the GeometricObject type.
• displayObject can be invoked by passing any instance of GeometricObject (e.g., new
• CircleFromSimpleGeometricObject(1, "red", false) and new Rectangle-
• FromSimpleGeometricObject(1, 1, "black", false)

• 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”).

• In simple terms, polymorphism means that a variable of a supertype can refer to a


subtype object.

}
-------------------------------------------------------------------------------------------------------------------------
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]());

• A variable must be declared a type.


• The type that declares a variable is called the variable’s declared type. Here o’s
declared type is Object.
• A variable of a reference type can hold a null value or a reference to an instance of
the declared type.
• The instance may be created using the constructor of the declared type or its
subtype.
• The actual type of the variable is the actual class for the object referenced by the
variable.
• Here o’s actual type is GeometricObject, because o references an object created
using new GeometricObject(). Which toString() method is invoked by o is
determined by o’s actual type
• This is known as dynamic binding.
• Dynamic binding works as follows: Suppose an object o is an instance of classes C1,
C2, . . . , Cn-1, and Cn, where C1 is a subclass of C2, C2 is a subclass of C3, . . . , and
Cn-1 is a subclass of Cn, as shown in Figure

• 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.

Dynamic binding .. [Link] :

public class DynamicBindingDemo {

public static void main(String[] args) {


m(new GraduateStudent());
m(new Student());
m(new Person());
m(new Object());
}
public static void m(Object x) {
[Link]([Link]());

class Person extends Object {


@Override
public String toString() {
return "Person" ;
}

}
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.

• The statement in Figure - a declares that c is a reference variable whose type is


Comparable and invokes the compareTo method to compare a Date object with a
string. The code compiles fine, but it has a runtime error because a string cannot be
compared with a date.

• The statement in Figure - b declares that c is a reference variable whose type is


Comparable<Date> and invokes the compareTo method to compare a Date object
with a string.
• This code generates a compile error, because the argument passed to the
compareTo method must be of the Date type.
• The errors can be detected at compile time rather than at runtime, the generic type
makes the program more reliable.

Generic programming .. The ArrayList Class


• An ArrayList object can be used to store a list of objects.
• Once the array is created, its size is fixed.
• Java provides the ArrayList class, which can be used to store an unlimited
number of objects.
• Methods in ArrayList :

• ArrayList is known as a generic class with a generic type E.


• A concrete type can be specified to replace E when creating an ArrayList.

• 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]> ();

Generic programming .. [Link] :

import [Link];
public class TestArrayList {

public static void main(String[] args) {


// Create a list to store cities
ArrayList<String> cityList = new ArrayList<>();
// Add some cities in the list
[Link]("London");
// cityList now contains [London]
[Link]("Denver");
// cityList now contains [London, Denver]
[Link]("Paris");

// cityList now contains [London, Denver, Paris]


[Link]("Miami");
// cityList now contains [London, Denver, Paris, Miami]
[Link]("Seoul");
// Contains [London, Denver, Paris, Miami, Seoul]

[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

// Insert a new city at index 2


[Link](2, "Xian");
// Contains [London, Denver, Xian, Paris, Miami, Seoul, Tokyo]
// Remove a city from the list
[Link]("Miami");

// Contains [London, Denver, Xian, Paris, Seoul, Tokyo]


// Remove a city at index 1
[Link](1);
// Contains [London, Xian, Paris, Seoul, Tokyo]
// Display the contents in the list

[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());
}

• A generic type can be defined for a static method.


• [Link]
public class GenericMethodDemo {

public static void main(String[] args ) {


Integer[] integers = {1, 2, 3, 4, 5};
String[] strings = {"London", "Paris", "New York", "Austin"};
GenericMethodDemo.<Integer>print(integers);
GenericMethodDemo.<String>print(strings);

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

The statement Object o = new Student(), known as implicit casting


• Explicit casting
• To assign the object reference o to a variable of the Student type using the
following statement:
Student b = (Student)o;
• Upcasting : To cast an instance of a subclass to a variable of a superclass as an
instance of a subclass is always an instance of its superclass.
• Downcasting: When casting an instance of a superclass to a variable of its subclass
(known as downcasting), explicit casting must be used to confirm your intention to
the compiler with the (SubclassName) cast notation.
Casting objects .. instanceof operator :

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 */

if (myObject instanceof Circle) {


[Link]("The circle diameter is " +
((Circle)myObject).getDiameter());
...
}

• 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.

Casting objects .. instanceof [Link] :


public class CastingDemo {
public static void main(String[] args) {
Object object1 = new CircleFromSimpleGeometricObject(1);

Object object2 = new RectangleFromSimpleGeometricObject(1, 1);


displayObject(object1);
displayObject(object2);
}
public static void displayObject(Object object) {

if (object instanceof CircleFromSimpleGeometricObject) {


[Link]("The circle area is "
+((CircleFromSimpleGeometricObject)object).getArea());
[Link]("The circle diameter is "
+((CircleFromSimpleGeometricObject)object).getDiameter());
}
else if (object instanceof RectangleFromSimpleGeometricObject) {
[Link]("The rectangle area is
"+((RectangleFromSimpleGeometricObject)object).getArea());
}
}

}
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]

public abstract class GeometricObject {


private String color = "white";

private boolean filled;


private [Link] dateCreated;
protected GeometricObject() {
dateCreated = new [Link]();
}
protected GeometricObject(String color, boolean filled) {

dateCreated = new [Link]();


[Link] = color;
[Link] = filled;
}
public String getColor() {

return color;
}
public void setColor(String color) {
[Link] = color;
}

public boolean isFilled() {


return filled;
}
public void setFilled(boolean filled) {

[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] :

public class Circle extends GeometricObject {


// Same as lines as in earlier Slides
}
[Link]
public class Rectangle extends GeometricObject {

// Same as lines in earlier Slides


}

Abstract class [Link] :


public class TestGeometricObject {

public static void main(String[] args) {


GeometricObject geoObject1 = new Circle(5);
GeometricObject geoObject2 = new Rectangle(5, 3);
[Link]("The two objects have the same area? "
+equalArea(geoObject1,geoObject2));
displayGeometricObject(geoObject1);

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 */

public static void displayGeometricObject(GeometricObject object) {


[Link]();
[Link]("The area is " + [Link]());
[Link]("The perimeter is " + [Link]());
}

Output:
The two objects have the same area? false
The area is 78.53981633974483

The perimeter is 31.41592653589793


The area is 13.0
The perimeter is 16.0
-------------------------------------------------------------------------------------
Interface in java :

• An interface is a class-like construct that contains only constants and abstract


methods.

• Java uses the following syntax to define an interface:


modifier interface InterfaceName {
/** Constant declarations */
/** Abstract method signatures */
}

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.

Interface in java .. [Link]

abstract class Animal {

/** Return animal sound */


public abstract String sound();
}
class Chicken extends Animal implements Edible {
@Override

public String howToEat() {


return "Chicken: Fry it";
}
@Override
public String sound() {
return "Chicken: cock-a-doodle-doo";
}
}
class Tiger extends Animal {

@Override
public String sound() {
return "Tiger: RROOAARR";
}
}

abstract class Fruit implements Edible {


// Data fields, constructors, and methods omitted here
}

class Apple extends Fruit {


@Override
public String howToEat() {
return "Apple: Make apple cider";
}

}
class Orange extends Fruit {
@Override
public String howToEat() {
return "Orange: Make orange juice";

Interface in java .. [Link] :


public class TestEdible {

public static void main(String[] args) {


Object[] objects = {new Tiger(), new Chicken(), new Apple()};
for (int i = 0; i < [Link]; i++) {
if (objects[i] instanceof Edible)
[Link](((Edible)objects[i]).howToEat());

if (objects[i] instanceof Animal) {


[Link](((Animal)objects[i]).sound());
}
}
}

Interface in java .. [Link] - output

Tiger: RROOAARR
Chicken: Fry it
Chicken: cock-a-doodle-doo

Apple: Make apple cider

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

• Application memory space is less (main memory)


• Application execution time is less
• Application performance is enhance (improve)
• Redundancy (repetition) of code is minimized
• Package provides access protection.
• Package removes naming collision.

Types of package :
• Classified as two types:
– Predefined or built-in package
– User defined package

• Predefined or built-in package


– As a part of java API, every predefined package is collection of predefined
classes, interfaces and sub-package.
• User defined package
– Design and Developed by the user
Supply as a part of their project to deal with common requirement
Rules to create user defined package :

• Package statement should be the first statement of any package program.


• Choose an appropriate class name or interface name and whose modifier must be
public.
• Any package program can contain only one public class or only one public interface
but it can contain any number of normal classes.
• Package program should not contain any main class (that means it should not
contain any main())
• Modifier of constructor of the class which is present in the package must be public.
(This is not applicable in case of interface because interface have no constructor.)
• The modifier of method of class or interface which is present in the package must be
public (This rule is optional in case of interface because interface methods by default
public)
• Every package program should be save either with public class name or public
Interface name
• Example:
Compile package programs :
• For compilation of package program first needs to save program with public
[Link] and to be compiled using below syntax:
• javac -d . [Link]
• javac -d path [Link]

• "-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
{

public void show()


{
[Link]("Sum method");
}
}
import mypack.A;

public class Hello


{
public static void main(String arg[])
{
A a=new 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 :

• Inheritance concept used to reuse the feature within the program


- between class to class,
- interface to interface
- interface to class
but not accessing the feature across the program.

• 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 :

• The package [Link] contains a number of useful classes and interfaces.

• Java depends directly on several of the classes in this package, and many programs
will find these classes indispensable.

• The classes and interfaces in [Link] include:


– The Hashtable class for implementing hashtables, or associative arrays.
– The Vector class, which supports variable-length arrays.
– The Enumeration interface for iterating through a collection of elements.
– The StringTokenizer class for parsing strings into distinct tokens separated by
delimiter characters.

– 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-------------------------------------------------

You might also like