Oops Unit II
Oops Unit II
UNIT II
INHERITANCE, PACKAGES AND INTERFACES : Overloading Methods – Objects as
Parameters – Returning Objects – Static - Nested and Inner Classes - Inheritance - Basics –
Types of Inheritance -Super keyword -Method Overriding – Dynamic Method Dispatch –
Abstract Classes – final with Inheritance - Packages and Interfaces - Pack ages – Packages and
Member Access – Importing Packages – Interfaces.
The passing and returning of objects between methods is a basic feature of Java programming
and is essential to creating reliable, modular programs. In this section, we will discuss passing
and returning objects in Java, exploring different kinds and methods along the way and
offering complete code examples for a comprehensive understanding.
In Java, passing objects involves more than just data transfer; it also involves managing the flow
of references to these objects. It presents a distinct set of considerations because Java adheres to
the reference passing paradigm. Objects involve passing the value of their reference rather than
the actual object, in contrast to primitive data types where values are supplied directly.
Method Parameters:
Java's handling of object references in method parameters adds a layer of complexity to object
passing. Understanding that Java transfers references by value is crucial. This means that instead
of the actual object, only the reference to it is transferred. Let's delve into a basic illustration to
clarify this concept:
Example :
class Person {
String name;
Person(String name) {
this.name = name;
}
}
public class ObjectPassingExample {
public static void modifyPersonName(Person person) {
person.name = "Ram Kumar";
}
public static void main(String[] args) {
Person person = new Person("Ravi");
System.out.println("Before modification: " + person.name);
modifyPersonName(person);
System.out.println("After modification: " + person.name);
}
}
OUTPUT:
Returning Objects:
Methods in Java can return objects, allowing for flexible and reusable code. Here's an example:
Example:
class Calculator {
IT/MVIT/IV SEM Page 3
IT T45 JAVA PROGRAMMING – UNIT II
int result;
Calculator(int initialValue) {
this.result = initialValue;
}
public Calculator add(int value) {
this.result += value;
return this;
}
public Calculator subtract(int value) {
this.result -= value;
return this;
}
}
public class ObjectReturningExample
{
public static void main(String[] args) {
Calculator calculator = new Calculator(10);
int finalResult = calculator.add(5).subtract(3).result;
System.out.println("Final result: " + finalResult);
}
}
OUTPUT:
Final result: 12
For example, to create an object for the static nested class, use this syntax:
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
INNER CLASSES:
Inner classes, also called Nested Classes, are nothing but classes that are defined within
other classes.
Java inner classes have feature that makes them richer and more useful. An object of an
inner class has an implicit reference to the outer class object that instantiated it. Through this
pointer, it gains access to any variable of the outer object. Only static inner classes don’t have
this pointer. It is actually invisible when we write the code, but compiler takes care of it. Inner
classes are actually a phenomenon of the compiler and not the JVM.
Inner classes may be defined with following access modifiers : public, protected, private,
or with default package access.
They can not only access the instance variables but local variables of the method (in
which they are defined) as well, but the local variable has to be declared final.
Syntax:-
class Subclass-name extends Superclass-name
{
//methods and fields
}
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.
Single Inheritance
When a class extends another one class only then we call it a single inheritance. The below
flow diagram shows that class B extends only one class which is A. Here A is a parent class of B
and B would be a child class of A.
import java.io.*;
class Player
{
String pname;
Player(String name1)
{
pname=name1;
}
void display()
{
System.out.println("Player Name:"+pname);
}
}
class Cricket extends Player
{
String pos;
Cricket(String name, String pos1)
IT/MVIT/IV SEM Page 7
IT T45 JAVA PROGRAMMING – UNIT II
{
super(name);
pos=pos1;
}
void output()
{
System.out.println("Cricket Player Details");
display();
System.out.println("Position:"+pos);
}
}
class Single
{
public static void main(String arg[])
{
Cricket c1=new Cricket("Sachin", "First");
Cricket c2=new Cricket("Dravid", "Fourth");
c1.output();
c2.output();
}
}
Multiple Inheritances
Java does not support the concept of multiple inheritances however this concept is
implemented using a secondary interface path in the form of interfaces. An interface in a class is
defined using implements.
Multilevel Inheritance
For this the common requirement is the use of the derived class as a super class . Here
the class A serves as a base class for the derived class B which in turn serves as the base class for
the derived class C. the chain ABC is known as inheritance path.
Class A
{
}
Class B extends A
{
}
IT/MVIT/IV SEM Page 8
IT T45 JAVA PROGRAMMING – UNIT II
Class C extends B
{
}
class Car
{
public Car()
{
System.out.println("Class Car");
}
public void vehicleType()
{
System.out.println("Vehicle Type: Car");
}
}
class Maruti extends Car
{
public Maruti()
{
System.out.println("Class Maruti");
}
public void brand()
{
System.out.println("Brand: Maruti");
}
public void speed()
{
System.out.println("Max: 90Kmph");
}
}
IT/MVIT/IV SEM Page 9
IT T45 JAVA PROGRAMMING – UNIT II
Hierarchial Inheritance
Using hierarchical inheritance many programming problems can be cast into a hierarchy
where certain features of one level are shared by many others below the level. This inheritance is
used as a support to the hierarchical design of a program.
Eg: hierarchical classification of accounts in a commercial bank
class Birds
{
public void fly()
{
System.out.println(“Generally,Birds fly”);
}
}
class Parrot extends Birds
{
Consider a scenario, Bank is a class that provides functionality to get rate of interest. But,
rate of interest varies according to banks. For example, SBI, ICICI and AXIS banks could
provide 8%, 7% and 9% rate of interest.
class Bank
{
int getRateOfInterest()
{
return 0;
}
}
class SBI extends Bank
{
int getRateOfInterest()
{
return 8;
}
}
class ICICI extends Bank
{
int getRateOfInterest()
{
return 7;
}
}
class AXIS extends Bank
{
int getRateOfInterest()
{
return 9;
IT/MVIT/IV SEM Page 13
IT T45 JAVA PROGRAMMING – UNIT II
}
}
class Test2
{
public static void main(String args[])
{
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9
abstract method
A method that is declared as abstract and does not have implementation is known as
abstract method.
class TestBank
{
public static void main(String args[])
{
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Output:-
Rate of Interest is: 7 %
Rate of Interest is: 8 %
r = a; // r refers to an A object
r.callme(); // calls A's version of callme
r = b; // r refers to a B object
r.callme(); // calls B's version of callme
r = c; // r refers to a C object
r.callme(); // calls C's version of callme
}
}
Output:-
Inside A's callme method
Inside B's callme method
Inside C's callme method
TYPES OF PACKAGES:
Packages are of two types. They are:
Java API Packages
User Defined Package
Java.langLanguage support classes. These are classes that Java compiler itself uses and
therefore itself uses and therefore they are automatically imported. They include classes
for primitive types, strings, math functions, threads and exceptions.
Java.utilLanguage utility classes such as vectors, hash tables, random numbers, date
etc..
Java.ioInput/Output support classes. They provide facilities for the input and output of
data.
Java.awtSet of packages for implementing graphical user interface. They include
classes for windows, buttons, lists, menus and so on.
Java.netClasses for networking. They include classes for communicating with local
computers as well as with internet servers.
Java.appletClasses for creating and implementing applets.
Java API
CREATING A PACKAGE:
Java system packages are organized and used. creating our own packages is by:
We must first declare the name of the packages using the package keyword followed by a
package name. This must be the first statement in a Java source file. Then we define a class, just
as we normally define a class. Here is an example:
Package first Package; // package declaration
Public class First-Class // class definition
IT/MVIT/IV SEM Page 20
IT T45 JAVA PROGRAMMING – UNIT II
{
……………….
……………….
………………
}
ACCESSING A PACKAGE:
A Java system package can be accessed either using a fully quantifies class name or using
a shortcut approach through the import statement. We can use the import statement when there
are many references to a particular package name are too long and unwidely.
}
public class division
{
public void div(int a,int b)
{
int c=a/b;
System.out.println( c );
}
}
import addsub.*;
import muldiv.*;
class TestPackage
{
public static void main(String arg[])
{
addition a=new addition();
a.add(10,20);
subtraction s=new subtraction();
s.sub(20,45);
multiplication m=new multiplication();
m.mul(5,6);
division d=new division();
d.div(2,5);
}
}
Output:-
30
-25
30
0
Finding Packages
Consider this package statement:
package myPackage;
In order for a program to find myPackage, one of the following must be true:
1) program is executed from the directory immediately above myPackage (the
parent of myPackage directory)
2) CLASSPATH must be set to include the path to myPackage
Example: Package
package MyPack;
class Balance
{
String name;
double bal;
Balance(String n, double b)
{
name = n;
bal = b;
}
void show()
{
if (bal<0)
{
System.out.print("-->> ");
}
System.out.println(name + ": $" + bal);
}
}
Example: Main
class AccountBalance
{
public static void main(String args[])
{
Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23);
current[1] = new Balance("Will Tell", 157.02);
current[2] = new Balance("Tom Jackson", -12.33);
for (int i=0; i<3; i++)
{
current[i].show();
}
}
}
Output:-
K. J. Fielding: $123.23
Will Tell: $157.02
-->> Tom Jackson: $-12.33
Importing of Packages
Since classes within packages must be fully-qualified with their package names, it would
be tedious to always type long dot-separated names.
The import statement allows to use classes or whole packages directly.
Importing of a concrete class:
import myPackage1.myPackage2.myClass;
Importing of all classes within a package:
import myPackage1.myPackage2.*;
Import Statement
The import statement occurs immediately after the package statement and before
the class statement:
package myPackage;
import otherPackage1;otherPackage2.otherClass;
class myClass { … }
The Java system accepts this import statement by default:
import java.lang.*;
This package includes the basic language functions. Without such functions, Java is of no
much use.
Example: Packages 1
A package MyPack with one public class Balance.
The class has two same-package variables: public constructor and a public show method.
package MyPack;
public class Balance
{
String name;
double bal;
public Balance(String n, double b)
{
IT/MVIT/IV SEM Page 24
IT T45 JAVA PROGRAMMING – UNIT II
name = n;
bal = b;
}
public void show()
{
if (bal<0)
{
System.out.print("-->> ");
}
System.out.println(name + ": $" + bal);
}
}
Example: Main
The importing code has access to the public class Balance of the MyPack package and its
two public members:
import MyPack.*;
class TestBalance
{
public static void main(String args[])
{
Balance test = new Balance("J. J. Jaspers", 99.88);
test.show();
}
}
Interface Definition
visibility mode interface interfaceName
{
constant variable declarations
IT/MVIT/IV SEM Page 25
IT T45 JAVA PROGRAMMING – UNIT II
Declaring Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to
declare an interface:
Example:
import java.lang.*;
public interface NameOfInterface
{
//Any number of final, static fields
//Any number of abstract method declarations\
}
Implementing Interfaces:
A class uses the implements keyword to implement an interface. The implements
keyword appears in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal
{
public void eat(){
System.out.println("Mammal eats");
}
public void travel(){
System.out.println("Mammal travels");
}
public int noOfLegs(){
return 0;
}
public static void main(String args[]){
MammalInt m = new MammalInt();
m.eat();
m.travel();
}}
This would produce following result:
Mammal eats
Mammal travels
Extending Interfaces:
An interface can extend another interface, similarly to the way that a class can extend
another class. The extends keyword is used to extend an interface, and the child interface
inherits the methods of the parent interface.
//Filename: Sports.java
public interface Sports
{
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
//Filename: Football.java
public interface Football extends Sports
{
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
Another Example:-
interface Maths1
{
void add();
}
interface Maths2
{
void sub();
}
interface Maths3
{
void mul();
}
}
}
As shown in the above diagram, a class extends another class, an interface extends another
interface but a class implements an interface.
Interface inheritance
A class implements interface but one interface extends another interface .
interface Printable
{
void print();
}
interface Showable extends Printable
{
void show();
}
class TestInterface4 implements Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
Output:
Hello
Welcome
Syntax
modifier class myClass
{ //class header
//field, constructor
//method declarations
};
Class Definition:
public class Vehicle
{ // syntax of class
int steering; // these are the instance variables
int wheels;
Vehicle(int wheelCpunt)
{ // Is a constructor of the class
wheels = wheelCount;
}
int getWheels()
{
return wheels;
}
}
In the above code snippet, public is a modifier and class keyword specifies that the
Vehicle is a type of Class, and the second and third lines are having two variables, these are
IT/MVIT/IV SEM Page 30
IT T45 JAVA PROGRAMMING – UNIT II
called instance variables and they hold the state of an object when instantiated. The fifth line
contains a Constructor for the class which will be called when an object is instantiated for the
vehicle, and sets the state of the object by giving them the passed values or default values.
In the above snippet when an Object of Vehicle is created, the state of wheels field is set
by the parameter to the constructor, and the steering is given a default value which is 0 for an
int.
Interface :
A Java Interface is also a virtual construct in programming world, but in contrary to the
Java Class, Interface cannot be instantiated or created as an object. An Interface denotes a group
of logical entities.
It can also act as a contract between two sub systems, while communicating with each
other.
The above code snippet, defines an interface called Vehicle. An interface will not have a
constructor and cannot be instantiated or an object cannot be created for this type. The variables
in an Interface are called Class variables / Static variables, since they cannot have instances they
should be able to communicate using the Class Name itself. In addition to being a static variables
these are also final by default which makes them not to be altered by any other objects.
State Each Object created will have its Each objected created after
own state implementing will have the same state
Behavior Every Object will have the same Every Object will have to define its
behavior unless overridden. own behavior by implementing the
contract defined.
Inheritance A Class can inherit only one An Interface cannot inherit any classes
Class and can implement many while it can extend many interfaces
interfaces
Variables All the variables are instance by All the variables are static final by
default unless otherwise specified default, and a value needs to be
assigned at the time of definition
Methods All the methods should be having All the methods are abstract by default
a definition unless decorated with and they will not have a definition.
an abstract keyword
class A
{
void msg()
{
System.out.println("Hello");
}
}
class B
{
void msg()
{
System.out.println("Welcome");
}
}
class C extends A,B //suppose if it were
{
Public Static void main(String args[])
{
C obj=new C();
obj.msg(); //Now which msg() method would be invoked?
}
}
Multiple inheritance is not supported through class in java but it is possible only by
interface.
Syntax:-
interface if1{}
interface if2{}
class MyClass implements if1,if2
{
// field, constructor, and
// method declarations
}
Example:-
interface Printable
{
void print();
}
interface Showable
{
void show();
}
class Multiple implements Printable, Showable
{
public void print()
{
System.out.println("Hello");
}
public void show()
{
System.out.println("Welcome");
}
public static void main(String args[])
{
Multiple obj = new Multiple();
obj.print();
obj.show();
}
}
Output:
Hello
Welcome
13. Write a Java program to maintain the books details like BookId, accession number;
book name, author, publication in books packages and keep the journal details such as
journal Id; journal name; in journal package in main class use these two packages details
for staff and student classes and display the books and journals information as requested
by the user.
package books;
class Book
{
int bookid;
String bookname;
String author;
String publication;
Book(int bid, String bname, String author, String publication)
{
this.bookid = bid;
this.bookname=bname;
this.author= author;
this.publication= publication;
}
Book getBooks()
{
return this;
}
}
package journals;
class Journal
{
int journalid;
String journalname;
Journal(int jid, String jname)
{
this.journalid=jid;
this.journalname=jname;
}
Journal getJournal()
{
return this;
}
import journal.*;
import books.*;
class Staff
{
Staff()
{
IT/MVIT/IV SEM Page 35
IT T45 JAVA PROGRAMMING – UNIT II
class Student
{
Student()
{
Book b = new Book(111, "JAVA PROGRAMMING", "HARI",
"PEARSON");
b.getBooks();
System.out.println(b.bookid);
System.out.println(b.bookname);
System.out.println(b.author);
System.out.println(b.publication);
}
}
class Access
{
public static void main(String args[])
{
Staff s= new Staff();
Student s1=new Student();
}
}