JAVA Unit 2
JAVA Unit 2
4
class SimpleInheritance
{
public static void main(String args[])
{
A superOb = new A();
B subOb = new B();
superOb.i = 10;
superOb.j = 20;
System.out.println("Contents of
superOb:");
superOb.showij();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of
subOb:");
subOb.showij();
subOb.showk();
System.out.println("Sum of i, j and k in
subOb:");
subOb.sum();
} 5
}
Output:
Contents of superOb:
i and j: 10 20
Contents of subOb:
i and j: 7 8
k: 9
Sum of i, j and k in subOb:
i+j+k: 24
6
single inheritance
7
A Superclass Variable Can Reference a
Subclass Object
The type of the reference variable determines what
members can be accessed, not the type of the object
8
Ex:-
class A
{
int x1=10;
void f1() { System.out.println("Superlass A"); }
}
class B extends A
{
int x2=20;
void f2() { System.out.println("Subclass B"); }
}
class RefDemo
{
public static void main(String args[ ])
{
A a1; // a1 is reference variable
a1=new A();
System.out.println(a1.x2); //wrong
a1.f2(); //wrong
}
9
}
In Which Order Constructors Are Called
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
10
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
class CallingCons {
public static void main(String args[]) {
C c = new C();
}
}
Output:-
Output:
i+j+k: 0
17
super uses
18
Using super to Call Super class Constructors
super(parameter-list);
19
– Compiler automatically inserts default form of
super ( super () ) in each constructor
20
Ex1:- Parameter constructor with super
class A
{
int i,j;
A(int ii) { i=ii; j=ii; System.out.println("A parameter constructor"); }
}
class B extends A
{
int k;
B(int kk) {
super(kk);
k=kk;
System.out.println("B parameter constructor");
}
void sum() {
System.out.println("i+j+k:" + (i+j+k));
} 21
}
class SimpleInheritance2
{
public static void main(String args[])
{
B subOb = new B(10);
subOb.sum();
}
}
Output:
A parameter constructor
B parameter constructor
i+j+k:30
22
Ex2:- constructors with out super
class A
{
int i,j;
A(){ i=10;j=20; System.out.println("A default constructor"); }
A(int ii) { i=ii; j=ii; System.out.println("A parameter
constructor");}
}
class B extends A
{
int k;
B() { k=20; System.out.println("B default constructor"); }
B(int kk) { k=kk; System.out.println("B parameter
constructor");}
23
void sum() {
System.out.println("i+j+k:" + (i+j+k));
}
}
class SimpleInheritance3
{
public static void main(String args[])
{
B subOb = new B(10);
subOb.sum();
}
} Output:
A default constructor
B parameter constructor
24
i+j+k:40
A Second Use of super
To access a member of the super class that is hidden
by a member of a sub class
general form:
super.member
• Single Inheritance
• Multilevel Inheritance
• Hierarchical Inheritance
29
Multiple Inheritance
30
Multilevel Inheritance
31
Hierarchical Inheritance
32
Hybrid Inheritance
• It is a combination of single inheritance and
multiple inheritance
• It is not supported by Java
• But, it can be achieved using interfaces
33
The Benefits of Inheritance
• Software Reusability ( among projects )
– Code ( class/package ) can be reused among the
projects
– Ex : code to insert a new element into a table can be
written once and reused
35
• Software Components
– Inheritance enables programmers to construct reusable
components
– The goal is to permit the development of new applications that
require little or no actual coding
– The java library offers a rich collection of software components
for use in the development of applications
36
• Information Hiding
– The programmer who reuses a software component
needs only to understand the nature of the
component and its interface
– He does not have to know the techniques used to
implement the component
37
Polymorphism
38
Method Overriding
39
Ex:-
class A {
int i, j;
A(int a, int b) { i=a; j=b;}
void show() {
System.out.println("i and j:"+i+" "+j); }
}
class B extends A {
int k;
B(int a, int b, int c) { super(a, b); k = c; }
void show() {
System.out.println("k: "+k); }
}
class Override {
public static void main(String args[ ]) {
B subOb = new B(1, 2, 3);
subOb.show(); }
40
} Output: k: 3
Dynamic Method Dispatch
41
Ex:-
class Dispatch {
class A {
public static void main(String
void callme() {
args[]) {
System.out.println("Inside A's
A a = new A();
callme method");
B b = new B();
}
C c = new C();
}
A r; //r is reference variable
class B extends A {
r = a;
void callme() {
r.callme();
System.out.println("Inside B's
callme method"); r = b;
} r.callme();
} r = c;
class C extends A { r.callme();
void callme() { }
System.out.println("Inside C's } Output:
callme method"); Inside A's callme method
Inside B's callme method
} 42
Inside C's callme method
}
Abstract Classes
A method that has been declared but not defined is an abstract
method
You must declare the abstract method with the keyword abstract:
abstract type name(parameter-list);
43
You can extend (subclass) an abstract class
44
Ex:-
abstract class Shape {
abstract void draw();
}
class Rectangle extends Shape {
void draw() {
System.out.println("drawing rectangle");
}
}
class Circle extends Shape {
void draw() {
System.out.println("drawing circle");
}
}
class TestAbstraction {
public static void main(String args[]) {
Rectangle r = new Rectangle();
r.draw();
Circle c = new Circle();
c.draw();
}
}
45
Ex:-
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest() { return 7;}
}
class PNB extends Bank{
int getRateOfInterest() { return 8;}
}
class TestBank
{
public static void main(String args[]){
SBI s = new SBI();
System.out.println("SBI Rate of Interest is: "+s.getRateOfInterest()+" %");
PNB p = new PNB();
System.out.println("PNB Rate of Interest is: "+p.getRateOfInterest()+" %");
}
}
46
Ex:-
abstract class A {
abstract void callme();
// concrete methods are still allowed in abstract classes
void callmetoo() {
System.out.println("This is a concrete method.");
}
}
class B extends A {
void callme() {
System.out.println("B's implementation of callme.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
} Output:
} B's implementation of callme.
This is a concrete method. 47
Ex:-
abstract class A
{
void callme() { System.out.println("This is A -callme method."); }
void callmetoo() { System.out.println("This is A-callmetoo method."); }
}
class B extends A {
void callme() {
System.out.println("This is B-callme method.");
}
}
class AbstractDemo {
public static void main(String args[]) {
B b = new B();
b.callme();
b.callmetoo();
} Output:
} This is B-callme method.
This is A-callmetoo method.
48
The keyword final has three uses
To create constant
To prevent overriding
To prevent inheritance
49
Using final to create constant
Ex:-
final float PI = 3.14f;
50
Using final to Prevent Overriding
Methods declared as final cannot be overridden
class A
{
final void meth()
{
System.out.println("This is a final method.");
}
}
class B extends A
{
void meth()
{
System.out.println("final method is overridden ");
}
} // ERROR! Can't override
51
Using final to Prevent Inheritance
Classes declared as final cannot be inherited
final class A {
// ...
}
// The following class is illegal
class B extends A { // ERROR! Can't subclass A
// ...
52
}
Base Class Object
There is one special class, Object,
defined by Java
In Java, all classes use inheritance
If no parent class is specified explicitly, the
base class Object is implicitly inherited
All classes defined in Java, is a child of
Object class, which provides minimal
functionality guaranteed to be common to
all objects
53
Object defines the following methods, which
means that they are available in every object
boolean equals(Object object)
--Determines whether one object equals to another object
Class getClass( )
--Obtains the class name of an object at run time
int hashCode( )
-- Returns the hash code associated with the
invoking object
String toString( )
--Returns a string that describes the object (name
of the class@hexadecimal representation of the 54
hashcode)
Ex:- base class object
class BaseClass
{
int i;
char c;
double d;
BaseClass() { i=1234; c='z'; d=3.14; }
void display() { System.out.println(i+"-"+c+"-"+d); }
}
class ObjectDemo
{
public static void main(String args[])
{
BaseClass b=new BaseClass();
BaseClass b1=new BaseClass();
b1=b;
b.display(); Output:
System.out.println(b.hashCode()); 1234-z-3.14
System.out.println(b.getClass()); 1671711
System.out.println(b.toString()); class BaseClass
System.out.println(b); BaseClass@19821f
System.out.println(b.equals(b1)); BaseClass@19821f
} true 55
}
Interfaces
• An interface, is a way of describing what classes
should do, without specifying how they should do it.
56
Defining an Interface
• The general form of an interface:
interface name
{
return-type method-name1(parameter-list);
return-type method-name2(parameter-list);
type final-varname1 = value;
type final-varname2 = value;
// ...
return-type method-nameN(parameter-list);
type final-varnameN = value;
57
}
• Variables can be declared inside of an interface, They are
implicitly static and final.
– They cannot be changed.
– They can be directly accessed by using interface name or
class name that implements interface.
58
Ex:-
interface I
{
59
Implementing Interfaces
• Once an interface has been defined, one or more classes can
implement that interface.
// class-body
}
60
• If a class implements more than one interface,
the interfaces are separated with a comma.
61
Example class that implements the Callback interface
class Client implements I
{ // Implement interface I
public void callback(int p)
{
System.out.println("callback called with " + p);
}
}
Ex:-
class Client implements I
{ // Implement Callback's interface
public void callback(int p)
{
System.out.println("callback called with " + p);
}
void nonIfaceMeth()
{
System.out.println("Classes that implement interfaces " +
"may also define other members, too.");
}
}
64
Partial Implementations
• If a class does not fully implement the methods defined by
the interface, then that class must be declared as abstract.
Ex:-
abstract class Incomplete implements I
{
int a, b;
void show()
{ System.out.println(a + " " + b); }
// ...
}
• Any class that inherits Incomplete must implement
callback( ) or be declared abstract itself.
65
Variables in Interfaces
• You can use interfaces to share constants among classes by
simply declaring an interface that contains variables which are
initialized to the desired values.
Ex:-
interface SharedConstants
{
int NO = 0;
int YES = 1;
int MAYBE = 2;
int LATER = 3;
int SOON = 4;
int NEVER = 5;
} 66
Methods in Interfaces
• Methods are Just declared.
67
Interfaces Can Be Extended
• One interface can inherit another by use of the keyword
extends.
68
Ex:-An Application using interfaces
interface A public void meth3()
{ {
void meth1();
System.out.println("Implement
void meth2();
meth3().");
}
interface B extends A
}
{ }
void meth3(); class IFExtend
} {
class MyClass implements B public static void main(String arg[])
{
{
public void meth1()
{ MyClass ob = new MyClass();
System.out.println("Implement meth1()."); ob.meth1();
} ob.meth2();
public void meth2() ob.meth3(); O/P:
{
} Implement meth1().
System.out.println("Implement meth2().");
} Implement meth2().
}
Implement meth3(). 69
Accessing Implementations Through Interface
References
• Any instance of any class that implements the
interface can be referred by an interface variable.
70
• The following example calls the callback( ) method
via an interface reference variable:
class TestIface {
public static void main(String args[]) {
Client c = new Client();
I iface = c;
iface.callback(42);
}
}
Note : iface can be used to access the callback( )
method, but it cannot be used to access any other
members of the Client class.
71
Example:
interface I {
int x=100;
void display();
}
class A implements I {
public void display() { System.out.println(" A display method"); }
void print() { System.out.println("A print method"); }
}
class MainClass {
public static void main(String args[]) {
I iface;
A a = new A();
iface=a;
iface.display();
System.out.println(iface.x);
iface.print(); Error 72
} }
Use of implements and extends
keyword
73
Differences between classes and
interfaces
• Interfaces has method declarations with out
any body
• Interfaces has instance variables which are
static and final
• Classes has to implement the interfaces
• Instances can not be created for interfaces
74
Use of Interfaces
• It acts as APIs (Application Programming
Interface)
• It means users can implement interfaces in its
own way (depends on the application)
• It is easy to add new features (like members)
to the interfaces
• It is used in multiple inheritance
75
Java does not support multiple inheritance through classes,
but Java supports multiple inheritance through interfaces (one
class can implement more than one interface)
Example:
interface X
{
void methodX( );
}
interface Y
{
void methodY( );
}
class MI implements X, Y {
public void methodX( )
{
System.out.println("Implementaion of methodX");
} 76
public void methodY( )
{
System.out.println("Implementaion of methodY");
}
}
class MIDemo {
public static void main(String args[ ]) {
MI m = new MI( );
m.methodX( );
m.methodY( );
}
}
77