0% found this document useful (0 votes)
10 views34 pages

Java-Unit 2 Inheritance and Polymorphism

The document covers Object-Oriented Programming (OOP) concepts in Java, focusing on inheritance, polymorphism, multithreading, and the Object class. It explains various types of inheritance, method overriding, and the significance of the Object class as the root of the inheritance hierarchy. Additionally, it discusses compile-time and runtime polymorphism, providing examples and explanations of method overloading and dynamic method dispatch.

Uploaded by

smithauk12122020
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)
10 views34 pages

Java-Unit 2 Inheritance and Polymorphism

The document covers Object-Oriented Programming (OOP) concepts in Java, focusing on inheritance, polymorphism, multithreading, and the Object class. It explains various types of inheritance, method overriding, and the significance of the Object class as the root of the inheritance hierarchy. Additionally, it discusses compile-time and runtime polymorphism, providing examples and explanations of method overloading and dynamic method dispatch.

Uploaded by

smithauk12122020
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 WITH JAVA

Unit-2
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.

Multithreading in java: Thread life cycle and methods, Runnable interface, Thread
synchronization, Exception handling with try catch-finally, Collections in java, Introduction to
JavaBeans and Network Programming.

SHWETHA RANI R S 1ST BCA Page 1


OBJECT ORIENTED PROGRAMMING WITH JAVA

INHERITANCE AND POLYMORPHISM

INHERITANCE IN JAVA

INHERITANCE:EXTENDING A CLASS

Creating a new class, reusing the properties of existing ones. The


mechanism of deriving a new class from an old one is called inheritance. The old
class is known as the base class or super class or parent class and the new one is
called the subclass or derived class or child class.
The idea behind inheritance in java is that you can create new class that are
built upon existing classes. When you inherit from an existing class, you can reuse
methods and fields of the parent class. Moreover, you can add new methods and fields in
your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-


child relationship.
Why use inheritance in java
• For Method Overriding(so runtime polymorphism can be achieved)

• For Code Reusability.


The inheritance allows subclasses to inherit all the variables and methods of
their parent classes. Inheritance may take different forms:

1. Single inheritance(only one super class)

2. Multiple inheritance(server super classes)

3. Hierarchical inheritance (one superclass, many subclasses)

4. Multi-level inheritance(derived from a derived class)

Java does not directly implement multiple inheritance. However, this concept
is implemented using a secondary inheritance path in the form of interfaces.

Defining a subclass:
A sub class is defined as:
Class subclassname extends superclassname

variable declaration;
methods declaration;

SHWETHA RANI R S 1ST BCA Page 2


OBJECT ORIENTED PROGRAMMING WITH JAVA

The keyword extends signifies that the properties of the super classname are
extended to the subclassname. (or) The extends keyword indicates that you are
making a new class that derives from an existing class. The meaning of "extends"
is to increase the functionality. The subclass will now contain its own variables
and methods as well those of the [Link] kind of situation occurs when we
want to add some more properties to an existing class without actually modifying
it.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given below,
Dog class inherits the Animal class, so there is the single inheritance.
General form of single inheritance Is:

SHWETHA RANI R S 1ST BCA Page 3


OBJECT ORIENTED PROGRAMMING WITH JAVA

SHWETHA RANI R S 1ST BCA Page 4


OBJECT ORIENTED PROGRAMMING WITH JAVA

class Animal
{
void eat()
{
[Link]("eating...");

Class Dog extends Animal

Void bark()

[Link](“barking…”);}

Class TestInheritance

Public static void main(String args[])

Dog d=new Dog(); [Link]();

[Link]();

Output:

Barking… eating…

Multilevel Inheritance Example

If a class is derived from the class,which is derived from another class.

Or

When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in the example
given below, BabyDog class inherits the Dog class which again inherits the Animal class, so there is a
SHWETHA RANI R S 1ST BCA Page 5
OBJECT ORIENTED PROGRAMMING WITH JAVA

multilevel inheritance.
General form
class baseclass
{
…..//data members
……//member functions
}
class derivedclass-1 extends baseclass
{
…..//data members
……//member functions
}
class derivedclass-2 extends derivedclass-1
{
…..//data members
……//member functions
}

Example programme

File: [Link]

Class Animal

Void eat()

[Link](“eating…”);

Class Dog extends Animal

Void bark()

[Link](“barking…”);

}
SHWETHA RANI R S 1ST BCA Page 6
OBJECT ORIENTED PROGRAMMING WITH JAVA

Class BabyDog extends Dog

Void weep()

[Link](“weeping…”);

Class TestInheritance2

Public static void main(String args[])

BabyDog d=new BabyDog(); [Link]();

[Link]();

[Link]();

Output

Weeping…

Barking….

Eating……

Hierarchical Inheritance

When two or more classes inherits a single class, it is known as hierarchical inheritance. In the example given
below, Dog and Cat classes inherits the Animal class, so there is hierarchical inheritance.
SHWETHA RANI R S 1ST BCA Page 7
OBJECT ORIENTED PROGRAMMING WITH JAVA

General form

Class baseclass

…..//data members

……//member functions

Class derivedclass-1 extends baseclass

…..//data members

……//member functions

Class derivedclass-2 extends baseclass

…..//data members

……//member functions
}

Example programme
Class Animal

Void eat()

[Link](“eating…”);

Class Dog extends Animal


SHWETHA RANI R S 1ST BCA Page 8
OBJECT ORIENTED PROGRAMMING WITH JAVA

Void bark()

[Link](“barking…”);

Class Cat extends Animal

Void meow()

[Link](“meowing…”);

Class TestInheritance3

Public static void main(String args[])

Cat c=new Cat(); [Link]();

[Link]();

//[Link]();//[Link]

}}

SHWETHA RANI R S 1ST BCA Page 9


OBJECT ORIENTED PROGRAMMING WITH JAVA

Output:
meowing...
eating...

SHWETHA RANI R S 1ST BCA Page 10


OBJECT ORIENTED PROGRAMMING WITH JAVA

APPLICATION OF SINGLE INHERITANCE


Class Room
{
int length:
int breadth:
Room (int x , int y)
{
length=x;
breadth= y;
}
int area()
{
return (length* breadth);
}
}
class BedRoom extends Room
{
int height;
BedRoom (int x, int y, int z)
{
super (x, y)
height = z;
}
int volume ()
{
return (length* breadth* height);
}
class InherTest
{
public static void main(String args[])
{
BedRoom rooml= new BedRoom (14,12,10);
int areal [Link](); //superclass method.
int volumel = [Link] (): //baseclass method
[Link]("Areal = "+areal):
[Link]("volume1 = " + volume1):
}
}
The output of Program is:
Areal 168
Volumel = 1680

The program defines a class room and extends it to another class bedroom. Note
that the class bedroom defines its own data members and [Link] sub class
bedroom now includes three instance variables, namely length, breadth and
height and two methods area and volume.

The constructor in the derived class uses the super keyword to pass values
SHWETHA RANI R S 1ST BCA Page 11
OBJECT ORIENTED PROGRAMMING WITH JAVA

that are required by the base constructor.

bedroomroom1 = new bedroom (14, 12 , 10 );

calls first the bedroom constructor method, which in turn calls the room
constructor method by using the super keyword. Finally the object room1 of the
subclass bedroom calls the method area defines in the super class as well as the
method volume defined in the subclass itself.

Subclass constructor:
A subclass constructor is used to construct the instance variables of both the subclass
and the [Link] subclass constructor uses the keyword super to invoke the
Constructor method of the [Link] keyword super is used subject to the
following conditions:

• Super may only be used within a subclass constructor method

• The call to super class constructor must appear as the first statement
within the subclass constructor.

• The parameters in the super call must match the order and type of the
instance variable declared in the super class.

OVERRIDING METHODS:
Defining a method in the subclass that has the same name, same arguments and same return
type as a method in the superclass.
When the method is called, the method defined in the subclass is invoked and executed
instead of the one in the superclass.

Usage of Java Method Overriding


• Method overriding is used to provide the specific implementation of a method which is already
provided by its superclass.
• Method overriding is used for runtime polymorphism
Rules for Java Method Overriding
• The method must have the same name as in the parent class
• The method must have the same parameter as in the parent class.
• There must be an IS-A relationship (inheritance).
• The return type Should be the same or a subtype of the return type declared in the original overridden
method in the Super class.

(or)
However, there may be occasions when we want an object to respond to the same method but
have different behaviour when that method is called. That means, we should override the method
defined in the super class. This is possible by defining a method in the subclass that has the same name,
same arguments and same return type as a method in the super class. Then, when that method is called,
the method defined in the sub class is invoked and executed instead of the one in the superclass. This
is known as overriding
SHWETHA RANI R S 1ST BCA Page 12
OBJECT ORIENTED PROGRAMMING WITH JAVA

Illustration of method overriding


class Super
{
int x;
Super (int x)
{
this.x = x;
}
void display ( )
{
[Link]("Super x = " +x);
}
Class Sub extends Super
{
int y;
sub (int x, int y)
{
super (x);
this.y = y;
}
void display ( )
{
[Link]("Super x = " + x);
[Link]("Sub y = +y);
}
}
class Override Test
public static void main(String args[])
{
Sub sl=new Sub (100, 200);
[Link]();
}
Output:
Super x = 100
Sub y =200

Object class in Java


Object class is present in [Link] package. The Object class is the parent class of all the classes in java by
default. In other words, it is the top most class of java. The Object class is beneficial if you want to refer any
object whose type you don't know. Notice that parent class reference variable can refer the child class object,
know as upcasting.
All the methods of Object class can be used by all the subclasses and arrays. The Object class provides
different methods to perform different operations on objects.
Every class in Java is directly or indirectly derived from the Object class. If a class does not extend any
other class then it is a direct child class of Object and if extends another class then it is indirectly derived.
Therefore the Object class methods are available to all Java classes. Hence Object class acts as a root of
inheritance hierarchy in any Java Program
Let's take an example, there is getObject() method that returns an object but it can be of

SHWETHA RANI R S 1ST BCA Page 13


OBJECT ORIENTED PROGRAMMING WITH JAVA

any type like Employee, Student etc, we can use Object class reference to refer that object. For example:

Object obj=getObject();

The Object class provides some common behaviors to all the objects such as object can be compared, object
can be cloned, object can be notified etc.

Methods of Object class


The Object class provides many methods. They are as follows:

• toString() Method
• hashCode() Method
• equals(Object obj) Method
• getClass() method
• finalize() method
• clone() method
• wait(), notify() notifyAll() Methods
toString() Method:
It's provide string representation or convert object to string form. you can override toString() method
to get your own String representation of objects.
public String toString()
{
// Can override and give own definition
}

hashCode() Method:
It's generate unique hashcode for each object. The main advantage of saving objects. It's used to
override for user defined objects for better performance like searching.
equals(Object obj) Method:
It's used to compare the two objects dynamically.
getClass() Method:
It's return runtime class object and used to get metadata information as well.
finalize() method:
This method call required to perform garbage collector.
clone() method:
It used to create the copy or clone of object.
wait(), notify() notifyAll() Methods:
These are used in multithreading.

POLYMORPHISM IN JAVA

SHWETHA RANI R S 1ST BCA Page 14


OBJECT ORIENTED PROGRAMMING WITH JAVA

The word polymorphism means having many forms. In simple words, we can define polymorphism
as the ability of a message to be displayed in more than one form.

Polymorphism is the ability of an object to take on many forms. The most common use of
polymorphism in OOP occurs when a parent class reference is used to refer to a child class object.
Any Java object that can pass more than one IS-A test is considered to be polymorphic

Real-life Illustration: Polymorphism

A person at the same time can have different characteristics. Like a man at the same time is a father,
a husband, an employee. So the same person possesses different behavior in different situations. This
is called polymorphism.
Polymorphism is considered one of the important features of Object-Oriented Programming.
Polymorphism allows us to perform a single action in different ways. In other words, polymorphism
allows you to define one interface and have multiple implementations. The word “poly” means many
and “morphs” means forms, So it means many forms.

Types of polymorphism

In Java polymorphism is mainly divided into two types:

• Compile-time Polymorphism
• Runtime Polymorphism

Type 1: Compile-time polymorphism

It is also known as static polymorphism. This type of polymorphism is achieved by function


overloading or operator overloading.

Method Overloading: When there are multiple functions with the same name but different
parameters then these functions are said to be overloaded. Functions can be overloaded by change in
the number of arguments or/and a change in the type of arguments.

SHWETHA RANI R S 1ST BCA Page 15


OBJECT ORIENTED PROGRAMMING WITH JAVA

Example 1
// Java Program for Method overloading
// By using Different Types of Arguments

class Helper {

// Method with 2 integer parameters

static int Multiply(int a, int b)

{
return a * b; // Returns product of integer numbers
}

// Method 2

// With same name but with 2 double parameters

static double Multiply(double a, double b)

{
return a * b; // Returns product of double numbers

}
}

// Class 2
// Main class

class GFG {

public static void main(String[] args) // Main driver method

{
// Calling method by passing

// input as in arguments

[Link]([Link](2, 4));

[Link]([Link](5.5, 6.3));
}
}
Output:
8
34.65
Type 2: Runtime polymorphism

SHWETHA RANI R S 1ST BCA Page 16


OBJECT ORIENTED PROGRAMMING WITH JAVA

Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an overridden


method is resolved at runtime rather than compile-time.
In this process, an overridden method is called through the reference variable of a superclass. The
determination of the method to be called is based on the object being referred to by the reference
variable.
Example:
class Shape
{
void draw()
. {
[Link]("drawing...");}
}
class Rectangle extends Shape
{
void draw()
{
[Link]("drawing rectangle...");
}
}
class Circle extends Shape
{
void draw()
{
[Link]("drawing circle...");
}
}
class Triangle extends Shape
{
void draw()
{
[Link]("drawing triangle...");
}
}
class TestPolymorphism2
{
public static void main(String args[])
{
Shape s;
s=new Rectangle();
[Link]();
s=new Circle();
[Link]();
s=new Triangle();
[Link]();
}
}

SHWETHA RANI R S 1ST BCA Page 17


OBJECT ORIENTED PROGRAMMING WITH JAVA

Casting objects
Upcasting and Downcasting in Java
A process of converting one data type to another is known
as Typecasting and Upcasting and Downcasting is the type of object typecasting. In Java, the
object can also be typecast like the datatypes. Parent and Child objects are two types of objects.
So, there are two types of typecasting possible for an object, i.e., Parent to Child and Child to
Parent or can say Upcasting and Downcasting.

Typecasting is used to ensure whether variables are correctly processed by a function or not.
In Upcasting and Downcasting, we typecast a child object to a parent object and a parent object
to a child object simultaneously. We can perform Upcasting implicitly or explicitly, but downcasting
cannot be implicitly possible.

1) Upcasting

Upcasting is a type of object typecasting in which a child object is typecasted to a parent class
object. By using the Upcasting, we can easily access the variables and methods of the parent class to
the child class. Here, we don't access all the variables and the method. We access only some specified
variables and methods of the child class. Upcasting is also known as Generalization and Widening.

[Link]

class Parent{

void PrintData()

[Link]("method of parent class");

class Child extends Parent

void PrintData()

[Link]("method of child class");

}
SHWETHA RANI R S 1ST BCA Page 18
OBJECT ORIENTED PROGRAMMING WITH JAVA

class UpcastingExample

public static void main(String args[])

Parent obj1 = (Parent) new Child();

Parent obj2 = (Parent) new Child();

[Link]();

[Link]();

2) Downcasting

Upcasting is another type of object typecasting. In Upcasting, we assign a parent class reference object
to the child class. In Java, we cannot assign a parent class reference object to the child class, but if we
perform downcasting, we will not get any compile-time error. However, when we run it, it throws
the "ClassCastException". Now the point is if downcasting is not possible in Java, then why is it
allowed by the compiler? In Java, some scenarios allow us to perform downcasting. Here, the subclass
object is referred by the parent class.

Below is an example of downcasting in which both the valid and the invalid scenarios are explained:

[Link]

//Parent class

class Parent {

String name;

void showMessage()

[Link]("Parent method is called");

SHWETHA RANI R S 1ST BCA Page 19


OBJECT ORIENTED PROGRAMMING WITH JAVA

class Child extends Parent

int age;

void showMessage()

[Link]("Child method is called");

public class Downcasting

public static void main(String[] args)

Parent p = new Child();

[Link] = "Shubham";

Child c = (Child)p;

[Link] = 18;

[Link]([Link]);

[Link]([Link]);

[Link]();

GENERIC PROGRAMMING

SHWETHA RANI R S 1ST BCA Page 20


OBJECT ORIENTED PROGRAMMING WITH JAVA

The Java Generics programming is introduced to deal with type-safe objects. It makes the code
stable by detecting the bugs at compile time. Before generics, we can store any type of objects in the
collection, i.e., non-generic. Now generics force the java programmer to store a specific type of
objects.

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-
defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to
create classes that work with different data types. An entity such as class, interface, or method that
operates on a parameterized type is a generic entity.
Why Generics?
The Object is the superclass of all other classes, and Object reference can refer to any object. These
features lack type safety. Generics add that type of safety feature. We will discuss that type of safety
feature in later examples
Types of Java Generics

Generic Method: Generic Java method takes a parameter and returns some value after performing a
task. It is exactly like a normal function, however, a generic method has type parameters that are
cited by actual type. This allows the generic method to be used in a more general way. The compiler
takes care of the type of safety which enables programmers to code easily since they do not have to
perform long, individual type castings.
Generic Classes: A generic class is implemented exactly like a non-generic class. The only
difference is that it contains a type parameter section. There can be more than one type of parameter,
separated by a comma. The classes, which accept one or more parameters, are known as
parameterized classes or parameterized types.
Generic Class
Like C++, we use <> to specify parameter types in generic class creation. To create objects of a
generic class, we use the following syntax.
// To create an instance of generic class

BaseType <Type> obj = new BaseType <Type> ()

// Java program to show working of user defined


// Generic classes
// We use < > to specify Parameter type
class Test<T>
{
T obj; // An object of type T is declared

Test(T obj)
{
[Link] = obj; } // constructor

public T getObject()
{
return [Link];
}
SHWETHA RANI R S 1ST BCA Page 21
OBJECT ORIENTED PROGRAMMING WITH JAVA

class Main // Driver class to test above


{
public static void main(String[] args)

{
Test<Integer> iObj = new Test<Integer>(15); // instance of Integer type

[Link]([Link]());

// instance of String type

Test<String> sObj = new Test<String>("BCA");

[Link]([Link]());
}}
Output
15
BCA

Instance of operator
The java instanceof operator is used to test whether the object is an instance of the specified
type (class or subclass or interface).
The instanceof in java is also known as type comparison operator because it compares the
instance with type. It returns either true or false. If we apply the instanceof operator with any
variable that has null value, it returns false.
Simple example of java instanceof
Let's see the simple example of instance operator where it tests the current class.
class Simple1
{
public static void main(String args[])
{
Simple1 s=new Simple1();
[Link](s instanceof Simple1); //true
}
}

Output:true

ABSTRAT CLASSES:
If the class acts as base class for many other classes and is not useful on its own, then we can
avoid instantiation and only it's declaration is enough. This is achieved by using abstract
keyword. Similarly we can have only method declaration and allow derived class to define it by
using abstract keyword. Such class is called abstract class and such method is called abstract
method. It can have abstract and non-abstract methods (method with the body).

SHWETHA RANI R S 1ST BCA Page 22


OBJECT ORIENTED PROGRAMMING WITH JAVA

We have seen that by making a method final we ensure that the method is not
redefined in a sub class. That is, the method can never be sub classed. Java allows us to
do something that is exactly opposite to this. That is, we can indicate that a method must
always be redefined in a sub class, thus making overriding compulsory. This is done using
the modifier keyword abstract in the method definition.
abstract class Bike{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
[Link]("running safely");
}
public static void main(String args[])
{
Bike obj = new Honda4();
[Link]();
}
}
Output:
running safely

A class which is declared as abstract is known as an abstract class. It can have abstract and non-
abstract methods. It needs to be extended and its method implemented. It cannot be instantiated.
When a class contains one or more abstract methods, it should also be declared
Abstract as shown in the example above.

While using abstract classes, we must satisfy the following conditions:

• We cannot use abstract classes to instantiate objects

directly. Eg: bike b =new bike( );

Is illegal because bike is an abstract class.

• The abstract methods of an abstract class must be defined in its subclass.


We cannot declare abstract constructors or abstract static method

INTERFACE IN JAVA

INTERFACES:MULTIPLE INHERITANCE

Java does not support multiple inheritance. That is, classes in Java cannot
have more than one superclass. For instance, a definition like:

SHWETHA RANI R S 1ST BCA Page 23


OBJECT ORIENTED PROGRAMMING WITH JAVA

Class A extends B extends C

.............................

.............................

Is not permitted in Java.a large number of real-life applications require the use of
multiple inheritance where by we inherit methods and properties from several
distinct classes.

Java provides an alternate approach known as interfaces to support the


concept of multiple [Link] a Java class cannot be a subclass of more
than one superclass, it can implement more than one interface, there by enabling
us to create classes that build up-on other classes without the problems created by
multiple inheritance.

DEFININGINTERFACES:

An interface is basically a kind of class. Like classes, interfaces contain


methods and variables but with a major difference. The difference is that interfaces
define only abstract methods and final fields. This means that interfaces do not
specify any code to implement these methods and data fields contain only
constants.

Interface interfacename

variable declaration;

methods declaration;

The syntax for defining an interface is very similar to that for defining a class.
Here, interface is the keyword and interfacename is any valid Java
variable(just like class names).
Note that all variables are declared as constants.
EXTENDINGINTERFACES

Like classes, interfaces can also be [Link] is, an interface can be


sub interfaced from other interfaces. The new subinterface will inherit all the

SHWETHA RANI R S 1ST BCA Page 24


OBJECT ORIENTED PROGRAMMING WITH JAVA

members of the super interface in the manner similar to [Link] is achieved


using the keyword extends.

Interface name2 extends name1

Body of name2

For example, we can put all the constants in one interface and the methods in the

Interface ItemConstants

Int code=1001 ;

String name=“Fan”;

Interface Item extends ItemConstants

Void display();

}
other. This will enable us to use the constants in classes where the methods are
not required. Example

IMPLEMENTING INTERFACES
Interfaces are 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 follows:
class classname implements interfacename
{
body of classname.
}

Here the class classname "implements" the interface interfacename. A more


general form of implementation may look like this:
class classname extends superclass

SHWETHA RANI R S 1ST BCA Page 25


OBJECT ORIENTED PROGRAMMING WITH JAVA

implements interface1, interface2,…….


{
body of classname
}
This shows that a class can extend another class while implementing interfaces.
Program :Implementing interfaces

interface Area // Interface defined


{
final static float pi = 3,14F;
float compute (float x, float y);
}
class Rectangle implements Area
{
return (x*y);
}
public float compute (float x, float y)
}
class Circle implements Area
{
public float compute (float x, float y)
{
return (pi*x*x);
}
}
class InterfaceTest
{
public static void main(String args[])
{
Rectangle rect = new Rectangle();
Circle cir = new Circle();
Area area;
area =rect;
[Link]("Area of Rectangle =+[Link](2.5,3.5));
[Link] ("Area of Circle = "+[Link](4.5,5.5));
}
}

Implementing Multiple Inheritance


Progam:Implementing multiple inheritance

class Student
{
int rollNumber;
void getNumber(int n)
{

SHWETHA RANI R S 1ST BCA Page 26


OBJECT ORIENTED PROGRAMMING WITH JAVA

rollNumber = n;
}
void putNumber ( )
{
[Link] (" Roll No : " + rollNumber);
}
}
class Test extends Student
float part1, part2;
void getMarks (float ml, float m2)
part1 = m1;
part2 = m2;
}
void putMarks ( )
{
[Link]("Marks obtained ");
[Link]("Part 1 = " + part 1);
[Link]("Part 2 = " + part 2);
}
}
interface Sports
{
float sportWt = [Link];
void putwt ();
}
class Results extends Test implements Sports
{
float total;
public void putWt ( )
{
[Link]("Sports Wt = " + sportWt);
}
void display ( )
{
total = partl+part2 + sportWt;
put Number();
putMarks();
putWt ();
[Link]("Total score = " + total);
}
}
class Hybrid
public static void main(String args[])
Results student1 = new Results();
[Link] (1234);
[Link] (27.5F, 33.0F);
[Link]();

SHWETHA RANI R S 1ST BCA Page 27


OBJECT ORIENTED PROGRAMMING WITH JAVA

Output of the Program 10.2:


Roll No : 1234
Marks obtained
Part1 = 27.5
Part2 = 33
Sports Wt = 6
Total score = 66.5

SHWETHA RANI R S 1ST BCA Page 28


OBJECT ORIENTED PROGRAMMING WITH JAVA

JAVA PACKAGES

INTRODUCTION:

Packages are Java’s way of grouping a variety of classes and / or interfaces


together. The grouping is usually done according to functionality. In fact, packages act
as“containers”for classes.

Benefits:

• The classes contained in the packages of other programs can be easily reused.

• In packages, classes can be unique compared with classes in other


packages. That is two classes in two different packages can have the same
name. They may be referred by their fully qualified name, comprising the
package name and the classname.

• Packages provide a way to “hide” classes thus preventing other


programs or packages from accessing classes that are meant for initernal
use only.

• Packages also provide a way for separating “design” from “coding”.


First we can design classes and decide their relationships, and then we can
implement the Java code needed for the methods. It is possible to change
the implementation of any method without affecting the rest of the design.

JAVA API PACKAGES:

Java API provides a large number of classes grouped into different


packages according to [Link] of the time we use the packages
available with the Java API. Table below shows the classes that belongs to each
package.

Java

lang util io awt net applet

SHWETHA RANI R S 1ST BCA Page 29


OBJECT ORIENTED PROGRAMMING WITH JAVA

FrequentlyusedAPIpackages

Packagename Contents

[Link] Language support classes. These are classes that Java compiler itself
uses and therefore they are automatically [Link] include
classes for primitive types, strings, math functions, threads
and exceptions.

[Link] Language utility classes such as vectors,hash tables,random


numbers,date, etc.,

[Link] Input/output support [Link] provide facilities for the input


and output of data.
[Link] Set of classes for implementing Graphical User interface(GUI).
They include classes for windows,buttons, lists,menus and soon.

[Link] Classes for [Link] include classes for communicating


with local computers as well as with internet servers.

[Link] Classes for creating and implementing applets.

The package keyword is used to create a package in java.

//save as [Link]

package mypack;

public class Simple{

public static void main(String args[]){

[Link]("Welcome to package");

How to access package from another package?


There are three ways to access the package from outside the package.

SHWETHA RANI R S 1ST BCA Page 30


OBJECT ORIENTED PROGRAMMING WITH JAVA

1. import package.*;

2. import [Link];

3. fully qualified name.

1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to the
current package.

Example of package that import the packagename.*


//save by [Link]

package pack;

public class A{

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

import pack.*;

class B{

public static void main(String args[]){

A obj = new A();

[Link]();

2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.

Example of package by import [Link]


//save by [Link]

package pack;

public class A{

SHWETHA RANI R S 1ST BCA Page 31


OBJECT ORIENTED PROGRAMMING WITH JAVA

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

import pack.A;

class B{

public static void main(String args[]){

A obj = new A();

[Link]();

3) Using fully qualified name


If you use fully qualified name then only declared class of this package will be accessible. Now there
is no need to import. But you need to use fully qualified name every time when you are accessing the
class or interface.

It is generally used when two packages have same class name e.g. [Link] and [Link] packages
contain Date class.

Example of package by import fully qualified name


//save by [Link]

package pack;

public class A{

public void msg(){[Link]("Hello");}

//save by [Link]

package mypack;

class B{

public static void main(String args[]){

pack.A obj = new pack.A();//using fully qualified name

[Link]();

SHWETHA RANI R S 1ST BCA Page 32


OBJECT ORIENTED PROGRAMMING WITH JAVA

[Link] Package

It contains the collections framework, legacy collection classes, event model, date and time facilities,
internationalization, and miscellaneous utility classes (a string tokenizer, a random-number generator,
and a bit array).

The package [Link] contains a number of useful classes and interfaces. Although the name of
the package might imply that these are utility classes, they are really more important than that. In
fact, 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

SHWETHA RANI R S 1ST BCA Page 33


OBJECT ORIENTED PROGRAMMING WITH JAVA

SHWETHA RANI R S 1ST BCA Page 34

You might also like