MODULE 3
Classes, Inheritance
1
Prepared by THAPASWINI P S
Prepared by THAPASWINI P S 2
Prepared by THAPASWINI P S 3
Classes: Classes fundamentals
• A class defines a new data type.
• Once defined, this new type can be used to
create objects of that type.
• Thus, a class is a template for an object, and
an object is an instance of a class.
4
Prepared by THAPASWINI P S
The General Form of a Class
class classname
{
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list)
{
// body of method
}
type methodnameN(parameter-list)
{
// body of method
}
}
5
Prepared by THAPASWINI P S
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
// assign values to mybox's instance variables
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
6
Prepared by THAPASWINI P S
7
Prepared by THAPASWINI P S
Example:
class Box {
double width;
double height;
double depth;
}
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Object Creation:
1. First, we must declare a variable of the class type. This variable
does not define an object. Instead, it is simply a variable that can
refer to an object.
2. Second, you must acquire an actual, physical copy of the object
and assign it to that variable. We can do this using the new
operator.
8
Prepared by THAPASWINI P S
• An object reference variable holds bits that represent
a way to access an object.
• It doesn’t hold the object itself, but it holds
something like a pointer. Or an address. Except, in
Java we don’t really know what is inside a reference
variable. We do know that whatever it is, it represents
one and only one object. And the JVM knows how to
use the reference to get to the object
9
Prepared by THAPASWINI P S
10
Prepared by THAPASWINI P S
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
What about b2 ?????
11
Prepared by THAPASWINI P S
class Box
{
double width;
double height;
double depth;
}
class Main {
public static void main(String args[])
{
Box b = new Box();
Box c=b;
c.width=20;
System.out.println("c width is " c.width);
b=null;
System.out.println("c width is " + c.width);
}
}
12
Prepared by THAPASWINI P S
class Box
{ double width;
double height;
double depth;
}
class Main {public static void main(String args[]) {
Box b = new Box();
Box c = new Box();
b.width=10;
c.width=20;
System.out.println("b width is " + b.width);
System.out.println("c width is " + c.width);
b=c;
System.out.println("b width is " + b.width);
c=null;
System.out.println("b width is " + c.width);
}
} 13
Prepared by THAPASWINI P S
Methods in java
14
Prepared by THAPASWINI P S
Adding a Method to the Box Class
class Box {
double width;
double height;
double depth;
void volume()
{
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
class BoxDemo3
{
public static void main(String args[])
{
Box mybox1 = new Box();
Box mybox2 = new Box();
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
mybox1.volume();
mybox2.volume();
}
}
15
Prepared by THAPASWINI P S
Returning a Value
class Box {
double width;
double height;
double depth;
double volume()
{
return width * height * depth;
}
}
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
} }
16
Prepared by THAPASWINI P S
17
Prepared by THAPASWINI P S
Constructors
• It can be tedious to initialize all of the variables
in a class each time an instance is created
• Java allows objects to initialize themselves
when they are created.
• This automatic initialization is performed
through the use of a constructor.
• A constructor initializes an object immediately
upon creation.
• It has the same name as the class in which it
resides and is syntactically similar to a method
but no return type 18
Prepared by THAPASWINI P S
class Box {
double width;
double height;
double depth;
Box() { Zero argument constructor
System.out.println("Constructing Box");
width = 10;
height = 10;
depth = 10;
}
double volume() {
return width * height * depth;
}
}
class BoxDemo6 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
} 19
Prepared by THAPASWINI P S
• When we do not explicitly define a constructor for a
class, then Java creates a default constructor for the
class.
• The default constructor automatically initializes all
instance variables to zero.
• Once you define your own constructor, the default
constructor is no longer used
Prepared by THAPASWINI P S 20
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d; PARAMETERIZED CONSTRUCTOR
}
double volume() {
return width * height * depth;
}}
class BoxDemo7 {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box(3, 6, 9);
double vol;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}}
21
Prepared by THAPASWINI P S
The this Keyword
• Sometimes a method will need to refer to the object
that invoked it. this can be used inside any method to
refer to the current object.
Box(double w, double h, double d) {
this.width = w;
this.height = h;
this.depth = d;
}
22
Prepared by THAPASWINI P S
Instance Variable Hiding
• it is illegal in Java to declare two local
variables with the same name inside the same
or enclosing scopes.
• Interestingly, we can have local variables,
including formal parameters to methods, which
overlap with the names of the class’ instance
variables.
23
Prepared by THAPASWINI P S
When a local variable has the same name as an instance
variable, the local variable hides the instance variable.
Box(double width, double height, double depth) {
width = width;
height = height;
depth = depth;
}
Prepared by THAPASWINI P S 24
Because this lets us refer directly to the object, we can
use it to resolve any name space collisions that might
occur between instance variables and local variables.
Box(double width, double height, double depth)
{
this.width = width;
this.height = height;
this.depth = depth;
}
Prepared by THAPASWINI P S 25
Garbage Collection
[VTU QP: Explain Java garbage collector.]
• java handles de allocation for you automatically
by Garbage Collector
• The technique that accomplishes this is called
garbage collection
• When no references to an object exist, that
object is assumed to be no longer needed, and
the memory occupied by the object can be
reclaimed.
26
Prepared by THAPASWINI P S
28
Prepared by THAPASWINI P S
The finalize( ) Method
• Sometimes an object will need to perform some action
when it is destroyed
• By using finalization, you can define specific actions
that will occur when an object is just about to be
reclaimed by the garbage collector.
• It is important to understand that finalize( ) is only
called just prior to garbage collection.
protected void finalize( )
{
// finalization code here
}
29
Prepared by THAPASWINI P S
Prepared by THAPASWINI P S 30
A Stack Class
Class called Stack that implements a stack for integers:
Prepared by THAPASWINI P S 31
Prepared by THAPASWINI P S 32
Prepared by THAPASWINI P S 33
Overloading Methods
• Two or more methods within the same class that share the
same name, as long as their parameter declarations are
different.
• When this is the case, the methods are said to be
overloaded, and the process is referred to as method
overloading.
• Method overloading is one of the ways that Java supports
polymorphism.
• When Java encounters a call to an overloaded method, it
simply executes the version of the method whose
parameters match the arguments used in the call.
34
Prepared by THAPASWINI P S
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a) {
System.out.println("a: " + a);
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
double test(double a) {
System.out.println("double a: " + a);
return a*a;
} }
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
result = ob.test(123.25);
System.out.println("Result of ob.test(123.25): " + result);
} }
35
Prepared by THAPASWINI P S
class OverloadDemo {
void test() {
System.out.println("No parameters");
}
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
void test(double a) {
System.out.println("Inside test(double) a: " + a);
}
}
class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
int i = 88;
ob.test();
ob.test(10, 20);
ob.test(i);
ob.test(123.2);
}
}
36
Prepared by THAPASWINI P S
Java’s automatic type conversions can play a role in overload resolution
Overloading Constructors
• In addition to overloading normal methods,
you can also overload constructor methods.
Prepared by THAPASWINI P S 37
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
Box() {
width = -1;
height = -1;
depth = -1;
}
Box(double len) {
width = height = depth = len;
}
double volume() {
return width * height * depth;
}} 38
Prepared by THAPASWINI P S
class OverloadCons {
public static void main(String args[]) {
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " +
vol);
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " +
vol);
vol = mycube.volume();
System.out.println("Volume of mycube is " +
vol);
}}
CONSTRUCTOR OVERLOADING
Using Objects as Parameters
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
boolean equals(Test o) {
if(o.a == a && o.b == b) return true;
else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22);
Test ob3 = new Test(-1, -1);
System.out.println("ob1 == ob2: " + ob1.equals(ob2));
System.out.println("ob1 == ob3: " + ob1.equals(ob3));
}
}
39
Prepared by THAPASWINI P S
So far, we have only been using simple types as parameters
to methods. However, it is both correct and common to
pass objects to methods.
A Closer Look at Argument Passing
call-by-value
• This approach copies the value of an argument
into the formal parameter of the subroutine.
• changes made to the parameter of the subroutine
have no effect on the argument.
call-by-reference
• reference to an argument is passed to the formal
parameter
• this reference is used to access the actual
argument specified in the call
40
Prepared by THAPASWINI P S
class Test {
void meth(int i, int j) {
i *= 2;
j /= 2;
}
}
class CallByValue {
public static void main(String args[]) {
Test ob = new Test();
int a = 15, b = 20;
System.out.println("a and b before call: " + a + " " + b);
ob.meth(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
}
41
Prepared by THAPASWINI P S
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
void meth(Test o) {
o.a *= 2;
o.b /= 2;
}
}
class CallByRef {
public static void main(String args[]) {
Test ob = new Test(15, 20);
System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b);
ob.meth(ob);
System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b);
}
}
42
Prepared by THAPASWINI P S
Recursion
• Java supports recursion.
• Recursion is the process of defining something
in terms of itself.
• recursion is the attribute that allows a method
to call itself.
43
Prepared by THAPASWINI P S
class Factorial {
int fact(int n) {
int result;
if(n==1) return 1;
result n * fact(n-1);
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
System.out.println("Factorial of 3 is " + f.fact(3));
System.out.println("Factorial of 4 is " + f.fact(4));
System.out.println("Factorial of 5 is " + f.fact(5));
}
}
44
Prepared by THAPASWINI P S
Introducing Access Control
• public
• private
• protected
45
Prepared by THAPASWINI P S
class Test {
int a;
public int b;
private int c;
void setc(int i)
{
c = i;
}
int getc()
{
return c;
}
} 46
Prepared by THAPASWINI P S
class AccessTest {
public static void main(String args[])
{
Test ob = new Test();
ob.a = 10;
ob.b = 20;
ob.c = 100;
ob.setc(100);
System.out.println("a, b, and c: " +
ob.a + " " +ob.b + " " + ob.getc());
}
}
Understanding static
• When a member is declared static, it can be
accessed before any objects of its class are created,
and without reference to any object.
• You can declare both methods and variables to be
static.
• Instance variables declared as static are, essentially,
global variables. When objects of its class are
declared, no copy of a static variable is made.
Instead, all instances of the class share the same
static variable.
47
Prepared by THAPASWINI P S
static methods have several restrictions:
• They can only call other static methods.
• They must only access static data.
• They cannot refer to this or super in any way
48
Prepared by THAPASWINI P S
class UseStatic
{
static int a = 3;
static int b;
static void meth(int x) {
System.out.println("x = " + x);
System.out.println("a = " + a);
System.out.println("b = " + b);
}
static {
System.out.println("Static block initialized.");
b = a * 4;
}
public static void main(String args[]) {
meth(42);
}
}
49
Prepared by THAPASWINI P S
• Outside of the class in which static are defined,
static methods and variables can be used
independently of any object.
• To do so, you need only specify the name of
their class followed by the dot operator.
• classname.method( )
• Here, classname is the name of the class in
which the static method is declared.
Prepared by THAPASWINI P S 50
Outside the class
class StaticDemo {
static int a = 42;
static int b = 99;
static void callme() {
System.out.println("a = " + a);
}
}
class StaticByName {
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
} 51
Prepared by THAPASWINI P S
Introducing final
• A variable can be declared as final. Doing so
prevents its contents from being modified.
• This means that you must initialize a final
variable when it is declared.
Prepared by THAPASWINI P S 52
• It is a common coding convention to choose all
uppercase identifiers for final variables.
• Variables declared as final do not occupy
memory on a per-instance basis. Thus, a
final variable is essentially a constant.
• The keyword final can also be applied to
methods.
Prepared by THAPASWINI P S 53
Arrays Revisited
• Specifically, the size of an array—that is, the
number of elements that an array can hold—is
found in its length instance variable.
• All arrays have this variable, and it will
always hold the size of the array.
Prepared by THAPASWINI P S 54
Prepared by THAPASWINI P S 55
Inheritance
56
Prepared by THAPASWINI P S
[VTU QP: Define and explain different types of
inheritance in Java.]
• Inheritance allows the creation of hierarchical
classifications.
• Using inheritance, we can create a general class that
defines traits common to a set of related items. This
class can then be inherited by other more specific
classes, each adding those things that are unique to it.
• In the terminology of Java, a class that is inherited is
called a superclass. The class that does the inheriting
is called a subclass.
• In java, we say that the subclass extends the super
class.
Prepared by THAPASWINI P S 57
• To inherit a class, you simply incorporate the
definition of one class into another by using
the extends keyword.
• The general form of a class declaration that
inherits a superclass is shown here:
Prepared by THAPASWINI P S 58
Single Level inheritance
class A {
int i, j;
void showij() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A {
int k;
void showk() {
System.out.println("k: " + k);
}
void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
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();
System.out.println();
subOb.i = 7;
subOb.j = 8;
subOb.k = 9;
System.out.println("Contents of subOb: ");
subOb.showij();
subOb.showk();
System.out.println();
System.out.println("Sum of i, j and k in subOb:");
subOb.sum();
}
}
59
Prepared by THAPASWINI P S
Member Access and Inheritance
• Subclass cannot access those members of the
superclass that have been declared as private.
• A subclass inherits all public instance
variables and methods of the superclass, but
does not inherit the private instance variables
and methods of the superclass.
Prepared by THAPASWINI P S 60
class A {
int i;
private int j;
void setij(int x, int y) {
i = x;
j = y;
}
}
class B extends A {
int total;
void sum() {
total = i + j;
}
}
class Access {
public static void main(String args[]) {
B subOb = new B();
subOb.setij(10, 12);
subOb.sum();
System.out.println("Total is " + subOb.total);
}
}
61
Prepared by THAPASWINI P S
Using super
• Whenever a subclass needs to refer to its
immediate superclass, it can do so by use of
the keyword super.
• super has two general forms:
1. It is used to invoke/ call the superclass’
constructor.
2. It is used to access a member of the
superclass that has been hidden by a member
of a subclass.
62
Prepared by THAPASWINI P S
1. Using super to Call Superclass Constructors
super(arg-list);
Here, arg-list specifies any arguments needed by the
constructor in the superclass. super( ) must always be
the first statement executed inside a subclass’
constructor.
Prepared by THAPASWINI P S 63
64
Prepared by THAPASWINI P S
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
void get()
{
System.out.println(width+" "+height+" "+depth);
}
}
class BoxWeight extends Box {
BoxWeight(double w, double h, double d) {
super(w,h,d);
}
}
class Main {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15);
mybox1.get();
}
}
Prepared by THAPASWINI P S 65
Output:
10.0 20.0 15.0
super( ) must always be the first statement
executed inside a subclass constructor.
Prepared by THAPASWINI P S 66
class Box {
double width;
double height;
double depth;
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
} }
class BoxWeight extends Box {
double weight;
BoxWeight(double w, double h, double d, double m) {
super(w,h,d);
weight = m;
} }
class DemoBoxWeight {
public static void main(String args[]) {
BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3);
} } 67
Prepared by THAPASWINI P S
A Second Use for super
• The second form of super always refers to the superclass of the
subclass in which it is used. This usage has the following
general form:
super.member
Here, member can be either a method or an instance variable.
Prepared by THAPASWINI P S 68
class A {
int i;
}
class B extends A {
int i;
B(int a, int b) {
super.i = a;
i = b;
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
69
Prepared by THAPASWINI P S
Creating a Multilevel Hierarchy(Multilevel Inheritance)
Class X {
public void methodX() {
System.out.println("Class X method");
}
}
Class Y extends X {
public void methodY() {
System.out.println("class Y method");
}
}
Class Z extends Y {
public void methodZ() {
System.out.println("class Z method");
}
}
70
Prepared by THAPASWINI P S
Class Multilevel{
public static void main(String args[]) {
Z obj = new Z();
obj.methodX();
obj.methodY();
obj.methodZ();
} }
When Constructors Are Called
[VTU QP: Explain with example, when constructors are called in class hierarchy]
class A {
A() {
System.out.println("Inside A's constructor.");
}
}
class B extends A {
B() {
System.out.println("Inside B's constructor.");
}
}
class C extends B {
C() {
System.out.println("Inside C's constructor.");
}
}
71
Prepared by THAPASWINI P S
•In a class hierarchy, constructors are called in order of derivation, from super class to
subclass.
Output:
Inside A’s constructor
Inside B’s constructor
Inside C’s constructor
class CallingCons {
public static void main(String
args[]) {
C obj = new C();
}
}
Method Overriding
[VTU QP: Compare and contrast method overloading and
method overriding with suitable example.]
• In a class hierarchy, when a method in a subclass has the same
name and type signature as a method in its superclass, then the
method in the subclass is said to override the method in the
superclass.
• When an overridden method is called from within a subclass, it
will always refer to the version of that method defined by the
subclass.
72
Prepared by THAPASWINI P S
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 extendsA {
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();
} }
73
Prepared by THAPASWINI P S
Output:
k: 3
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
void show() {
super.show(); // this calls A's show()
System.out.println("k: " + k);
}
}
74
Prepared by THAPASWINI P S
If we wish to access the superclass version of an overridden method, you can
do so by using super.
Method Overloading
• Method overriding occurs only when the names and the type
signatures of the two methods are identical. If they are not,
then the two methods are simply overloaded.
Prepared by THAPASWINI P S 75
class A {
int i, j;
A(int a, int b) {
i = a;
j = b;
}
// display i and j
void show() {
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.
class B extends A {
int k;
B(int a, int b, int c) {
super(a, b);
k = c;
}
// overload show()
void show(String msg) {
System.out.println(msg + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show("This is k: "); // this calls show() in B
subOb.show(); // this calls show() in A
}
}
Output:
This is k: 3
i and j: 1 2
Dynamic Method Dispatch
• Dynamic method dispatch is the mechanism by which a
call to an overridden method is resolved at run time,
rather than compile time.
• Dynamic method dispatch is important because this is
how Java implements run-time polymorphism.
• It is the type of the object being referred to determines
which version of an overridden method will be executed.
76
Prepared by THAPASWINI P S
class A {
void callme() {
System.out.println("Inside A's callme
method");
}
}
class B extends A {
// override callme()
void callme() {
System.out.println("Inside B's callme
method");
}
}
class C extends A {
// override callme()
void callme() {
System.out.println("Inside C's callme
method");
}
} Prepared by THAPASWINI P S 77
Output:
Inside A’s callme method
Inside B’s callme method
Inside C’s callme method
class Dispatch {
public static void main(String args[]) {
A a = new A(); // object of type A
B b = new B(); // object of type B
C c = new C(); // object of type C
A r; // obtain a reference of type A
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
}
}
Abstract Classes
• An abstract class means that nobody can ever make a
new instance of that class.
• We can still use that abstract class as a declared
reference type, for the purpose of polymorphism, but
you don’t have to worry about somebody making
objects of that type. The compiler guarantees it.
78
Prepared by THAPASWINI P S
abstract class Animal
{
public void roam()
{
System.out.println(" Animal Roam");
}
}
class Dog extends Animal
{
public void roam()
{
System.out.println(" Dog Roam");
}
}
public class Main
{
public static void main(String[] args) {
Animal a=new Animal();
Dog c=new Dog();
c.roam();
}
}
Prepared by THAPASWINI P S 79
Abstract methods
• Sometimes we will want to create a superclass
that only defines a generalized form that will be
shared by all of its subclasses, leaving it to each
subclass to fill in the details. Such a class
determines the nature of the methods that the
subclasses must implement.
• An abstract method has no body!
• Only Prototype of the method inside class.
Prepared by THAPASWINI P S 80
// A Simple demonstration of abstract.
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();
}
}
Prepared by THAPASWINI P S 81
Using final with Inheritance
• The following are the two uses of final which apply to
inheritance.
i) Using final to Prevent Overriding
• ii) Using final to Prevent Inheritance
82
Prepared by THAPASWINI P S
i) Using final to Prevent Overriding
• To disallow a method from being overridden, specify
final as a modifier at the start of its declaration.
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() { // ERROR! Can't override.
System.out.println("Illegal!");
}
}
Prepared by THAPASWINI P S 83
ii) Using final to Prevent Inheritance
final class A{
}
// The following class is illegal.
class B extends A {
// ...
}
84
Prepared by THAPASWINI P S
final Variables?????
Prepared by THAPASWINI P S 85

Java-Module 3-PPT-TPS.pdf.Java-Module 3-PPT-TPS.pdf

  • 1.
  • 2.
  • 3.
  • 4.
    Classes: Classes fundamentals •A class defines a new data type. • Once defined, this new type can be used to create objects of that type. • Thus, a class is a template for an object, and an object is an instance of a class. 4 Prepared by THAPASWINI P S
  • 5.
    The General Formof a Class class classname { type instance-variable1; type instance-variable2; // ... type instance-variableN; type methodname1(parameter-list) { // body of method } type methodnameN(parameter-list) { // body of method } } 5 Prepared by THAPASWINI P S
  • 6.
    class Box { doublewidth; double height; double depth; } // This class declares an object of type Box. class BoxDemo { public static void main(String args[]) { Box mybox = new Box(); double vol; // assign values to mybox's instance variables mybox.width = 10; mybox.height = 20; mybox.depth = 15; // compute volume of box vol = mybox.width * mybox.height * mybox.depth; System.out.println("Volume is " + vol); } } 6 Prepared by THAPASWINI P S
  • 7.
  • 8.
    Example: class Box { doublewidth; double height; double depth; } Box mybox; // declare reference to object mybox = new Box(); // allocate a Box object Object Creation: 1. First, we must declare a variable of the class type. This variable does not define an object. Instead, it is simply a variable that can refer to an object. 2. Second, you must acquire an actual, physical copy of the object and assign it to that variable. We can do this using the new operator. 8 Prepared by THAPASWINI P S
  • 9.
    • An objectreference variable holds bits that represent a way to access an object. • It doesn’t hold the object itself, but it holds something like a pointer. Or an address. Except, in Java we don’t really know what is inside a reference variable. We do know that whatever it is, it represents one and only one object. And the JVM knows how to use the reference to get to the object 9 Prepared by THAPASWINI P S
  • 10.
  • 11.
    Assigning Object ReferenceVariables Box b1 = new Box(); Box b2 = b1; // ... b1 = null; What about b2 ????? 11 Prepared by THAPASWINI P S
  • 12.
    class Box { double width; doubleheight; double depth; } class Main { public static void main(String args[]) { Box b = new Box(); Box c=b; c.width=20; System.out.println("c width is " c.width); b=null; System.out.println("c width is " + c.width); } } 12 Prepared by THAPASWINI P S
  • 13.
    class Box { doublewidth; double height; double depth; } class Main {public static void main(String args[]) { Box b = new Box(); Box c = new Box(); b.width=10; c.width=20; System.out.println("b width is " + b.width); System.out.println("c width is " + c.width); b=c; System.out.println("b width is " + b.width); c=null; System.out.println("b width is " + c.width); } } 13 Prepared by THAPASWINI P S
  • 14.
    Methods in java 14 Preparedby THAPASWINI P S
  • 15.
    Adding a Methodto the Box Class class Box { double width; double height; double depth; void volume() { System.out.print("Volume is "); System.out.println(width * height * depth); } } class BoxDemo3 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; mybox1.volume(); mybox2.volume(); } } 15 Prepared by THAPASWINI P S
  • 16.
    Returning a Value classBox { double width; double height; double depth; double volume() { return width * height * depth; } } class BoxDemo4 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; mybox1.width = 10; mybox1.height = 20; mybox1.depth = 15; mybox2.width = 3; mybox2.height = 6; mybox2.depth = 9; vol = mybox1.volume(); System.out.println("Volume is " + vol); vol = mybox2.volume(); System.out.println("Volume is " + vol); } } 16 Prepared by THAPASWINI P S
  • 17.
  • 18.
    Constructors • It canbe tedious to initialize all of the variables in a class each time an instance is created • Java allows objects to initialize themselves when they are created. • This automatic initialization is performed through the use of a constructor. • A constructor initializes an object immediately upon creation. • It has the same name as the class in which it resides and is syntactically similar to a method but no return type 18 Prepared by THAPASWINI P S
  • 19.
    class Box { doublewidth; double height; double depth; Box() { Zero argument constructor System.out.println("Constructing Box"); width = 10; height = 10; depth = 10; } double volume() { return width * height * depth; } } class BoxDemo6 { public static void main(String args[]) { Box mybox1 = new Box(); Box mybox2 = new Box(); double vol; vol = mybox1.volume(); System.out.println("Volume is " + vol); vol = mybox2.volume(); System.out.println("Volume is " + vol); } } 19 Prepared by THAPASWINI P S
  • 20.
    • When wedo not explicitly define a constructor for a class, then Java creates a default constructor for the class. • The default constructor automatically initializes all instance variables to zero. • Once you define your own constructor, the default constructor is no longer used Prepared by THAPASWINI P S 20
  • 21.
    class Box { doublewidth; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; PARAMETERIZED CONSTRUCTOR } double volume() { return width * height * depth; }} class BoxDemo7 { public static void main(String args[]) { Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(3, 6, 9); double vol; vol = mybox1.volume(); System.out.println("Volume is " + vol); vol = mybox2.volume(); System.out.println("Volume is " + vol); }} 21 Prepared by THAPASWINI P S
  • 22.
    The this Keyword •Sometimes a method will need to refer to the object that invoked it. this can be used inside any method to refer to the current object. Box(double w, double h, double d) { this.width = w; this.height = h; this.depth = d; } 22 Prepared by THAPASWINI P S
  • 23.
    Instance Variable Hiding •it is illegal in Java to declare two local variables with the same name inside the same or enclosing scopes. • Interestingly, we can have local variables, including formal parameters to methods, which overlap with the names of the class’ instance variables. 23 Prepared by THAPASWINI P S
  • 24.
    When a localvariable has the same name as an instance variable, the local variable hides the instance variable. Box(double width, double height, double depth) { width = width; height = height; depth = depth; } Prepared by THAPASWINI P S 24
  • 25.
    Because this letsus refer directly to the object, we can use it to resolve any name space collisions that might occur between instance variables and local variables. Box(double width, double height, double depth) { this.width = width; this.height = height; this.depth = depth; } Prepared by THAPASWINI P S 25
  • 26.
    Garbage Collection [VTU QP:Explain Java garbage collector.] • java handles de allocation for you automatically by Garbage Collector • The technique that accomplishes this is called garbage collection • When no references to an object exist, that object is assumed to be no longer needed, and the memory occupied by the object can be reclaimed. 26 Prepared by THAPASWINI P S
  • 27.
  • 28.
    The finalize( )Method • Sometimes an object will need to perform some action when it is destroyed • By using finalization, you can define specific actions that will occur when an object is just about to be reclaimed by the garbage collector. • It is important to understand that finalize( ) is only called just prior to garbage collection. protected void finalize( ) { // finalization code here } 29 Prepared by THAPASWINI P S
  • 29.
  • 30.
    A Stack Class Classcalled Stack that implements a stack for integers: Prepared by THAPASWINI P S 31
  • 31.
  • 32.
  • 33.
    Overloading Methods • Twoor more methods within the same class that share the same name, as long as their parameter declarations are different. • When this is the case, the methods are said to be overloaded, and the process is referred to as method overloading. • Method overloading is one of the ways that Java supports polymorphism. • When Java encounters a call to an overloaded method, it simply executes the version of the method whose parameters match the arguments used in the call. 34 Prepared by THAPASWINI P S
  • 34.
    class OverloadDemo { voidtest() { System.out.println("No parameters"); } void test(int a) { System.out.println("a: " + a); } void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } double test(double a) { System.out.println("double a: " + a); return a*a; } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); double result; ob.test(); ob.test(10); ob.test(10, 20); result = ob.test(123.25); System.out.println("Result of ob.test(123.25): " + result); } } 35 Prepared by THAPASWINI P S
  • 35.
    class OverloadDemo { voidtest() { System.out.println("No parameters"); } void test(int a, int b) { System.out.println("a and b: " + a + " " + b); } void test(double a) { System.out.println("Inside test(double) a: " + a); } } class Overload { public static void main(String args[]) { OverloadDemo ob = new OverloadDemo(); int i = 88; ob.test(); ob.test(10, 20); ob.test(i); ob.test(123.2); } } 36 Prepared by THAPASWINI P S Java’s automatic type conversions can play a role in overload resolution
  • 36.
    Overloading Constructors • Inaddition to overloading normal methods, you can also overload constructor methods. Prepared by THAPASWINI P S 37
  • 37.
    class Box { doublewidth; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } Box() { width = -1; height = -1; depth = -1; } Box(double len) { width = height = depth = len; } double volume() { return width * height * depth; }} 38 Prepared by THAPASWINI P S class OverloadCons { public static void main(String args[]) { Box mybox1 = new Box(10, 20, 15); Box mybox2 = new Box(); Box mycube = new Box(7); double vol; vol = mybox1.volume(); System.out.println("Volume of mybox1 is " + vol); vol = mybox2.volume(); System.out.println("Volume of mybox2 is " + vol); vol = mycube.volume(); System.out.println("Volume of mycube is " + vol); }} CONSTRUCTOR OVERLOADING
  • 38.
    Using Objects asParameters class Test { int a, b; Test(int i, int j) { a = i; b = j; } boolean equals(Test o) { if(o.a == a && o.b == b) return true; else return false; } } class PassOb { public static void main(String args[]) { Test ob1 = new Test(100, 22); Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -1); System.out.println("ob1 == ob2: " + ob1.equals(ob2)); System.out.println("ob1 == ob3: " + ob1.equals(ob3)); } } 39 Prepared by THAPASWINI P S So far, we have only been using simple types as parameters to methods. However, it is both correct and common to pass objects to methods.
  • 39.
    A Closer Lookat Argument Passing call-by-value • This approach copies the value of an argument into the formal parameter of the subroutine. • changes made to the parameter of the subroutine have no effect on the argument. call-by-reference • reference to an argument is passed to the formal parameter • this reference is used to access the actual argument specified in the call 40 Prepared by THAPASWINI P S
  • 40.
    class Test { voidmeth(int i, int j) { i *= 2; j /= 2; } } class CallByValue { public static void main(String args[]) { Test ob = new Test(); int a = 15, b = 20; System.out.println("a and b before call: " + a + " " + b); ob.meth(a, b); System.out.println("a and b after call: " + a + " " + b); } } 41 Prepared by THAPASWINI P S
  • 41.
    class Test { inta, b; Test(int i, int j) { a = i; b = j; } void meth(Test o) { o.a *= 2; o.b /= 2; } } class CallByRef { public static void main(String args[]) { Test ob = new Test(15, 20); System.out.println("ob.a and ob.b before call: " +ob.a + " " + ob.b); ob.meth(ob); System.out.println("ob.a and ob.b after call: " +ob.a + " " + ob.b); } } 42 Prepared by THAPASWINI P S
  • 42.
    Recursion • Java supportsrecursion. • Recursion is the process of defining something in terms of itself. • recursion is the attribute that allows a method to call itself. 43 Prepared by THAPASWINI P S
  • 43.
    class Factorial { intfact(int n) { int result; if(n==1) return 1; result n * fact(n-1); return result; } } class Recursion { public static void main(String args[]) { Factorial f = new Factorial(); System.out.println("Factorial of 3 is " + f.fact(3)); System.out.println("Factorial of 4 is " + f.fact(4)); System.out.println("Factorial of 5 is " + f.fact(5)); } } 44 Prepared by THAPASWINI P S
  • 44.
    Introducing Access Control •public • private • protected 45 Prepared by THAPASWINI P S
  • 45.
    class Test { inta; public int b; private int c; void setc(int i) { c = i; } int getc() { return c; } } 46 Prepared by THAPASWINI P S class AccessTest { public static void main(String args[]) { Test ob = new Test(); ob.a = 10; ob.b = 20; ob.c = 100; ob.setc(100); System.out.println("a, b, and c: " + ob.a + " " +ob.b + " " + ob.getc()); } }
  • 46.
    Understanding static • Whena member is declared static, it can be accessed before any objects of its class are created, and without reference to any object. • You can declare both methods and variables to be static. • Instance variables declared as static are, essentially, global variables. When objects of its class are declared, no copy of a static variable is made. Instead, all instances of the class share the same static variable. 47 Prepared by THAPASWINI P S
  • 47.
    static methods haveseveral restrictions: • They can only call other static methods. • They must only access static data. • They cannot refer to this or super in any way 48 Prepared by THAPASWINI P S
  • 48.
    class UseStatic { static inta = 3; static int b; static void meth(int x) { System.out.println("x = " + x); System.out.println("a = " + a); System.out.println("b = " + b); } static { System.out.println("Static block initialized."); b = a * 4; } public static void main(String args[]) { meth(42); } } 49 Prepared by THAPASWINI P S
  • 49.
    • Outside ofthe class in which static are defined, static methods and variables can be used independently of any object. • To do so, you need only specify the name of their class followed by the dot operator. • classname.method( ) • Here, classname is the name of the class in which the static method is declared. Prepared by THAPASWINI P S 50
  • 50.
    Outside the class classStaticDemo { static int a = 42; static int b = 99; static void callme() { System.out.println("a = " + a); } } class StaticByName { public static void main(String args[]) { StaticDemo.callme(); System.out.println("b = " + StaticDemo.b); } } 51 Prepared by THAPASWINI P S
  • 51.
    Introducing final • Avariable can be declared as final. Doing so prevents its contents from being modified. • This means that you must initialize a final variable when it is declared. Prepared by THAPASWINI P S 52
  • 52.
    • It isa common coding convention to choose all uppercase identifiers for final variables. • Variables declared as final do not occupy memory on a per-instance basis. Thus, a final variable is essentially a constant. • The keyword final can also be applied to methods. Prepared by THAPASWINI P S 53
  • 53.
    Arrays Revisited • Specifically,the size of an array—that is, the number of elements that an array can hold—is found in its length instance variable. • All arrays have this variable, and it will always hold the size of the array. Prepared by THAPASWINI P S 54
  • 54.
  • 55.
    Inheritance 56 Prepared by THAPASWINIP S [VTU QP: Define and explain different types of inheritance in Java.]
  • 56.
    • Inheritance allowsthe creation of hierarchical classifications. • Using inheritance, we can create a general class that defines traits common to a set of related items. This class can then be inherited by other more specific classes, each adding those things that are unique to it. • In the terminology of Java, a class that is inherited is called a superclass. The class that does the inheriting is called a subclass. • In java, we say that the subclass extends the super class. Prepared by THAPASWINI P S 57
  • 57.
    • To inherita class, you simply incorporate the definition of one class into another by using the extends keyword. • The general form of a class declaration that inherits a superclass is shown here: Prepared by THAPASWINI P S 58 Single Level inheritance
  • 58.
    class A { inti, j; void showij() { System.out.println("i and j: " + i + " " + j); } } class B extends A { int k; void showk() { System.out.println("k: " + k); } void sum() { System.out.println("i+j+k: " + (i+j+k)); } } 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(); System.out.println(); subOb.i = 7; subOb.j = 8; subOb.k = 9; System.out.println("Contents of subOb: "); subOb.showij(); subOb.showk(); System.out.println(); System.out.println("Sum of i, j and k in subOb:"); subOb.sum(); } } 59 Prepared by THAPASWINI P S
  • 59.
    Member Access andInheritance • Subclass cannot access those members of the superclass that have been declared as private. • A subclass inherits all public instance variables and methods of the superclass, but does not inherit the private instance variables and methods of the superclass. Prepared by THAPASWINI P S 60
  • 60.
    class A { inti; private int j; void setij(int x, int y) { i = x; j = y; } } class B extends A { int total; void sum() { total = i + j; } } class Access { public static void main(String args[]) { B subOb = new B(); subOb.setij(10, 12); subOb.sum(); System.out.println("Total is " + subOb.total); } } 61 Prepared by THAPASWINI P S
  • 61.
    Using super • Whenevera subclass needs to refer to its immediate superclass, it can do so by use of the keyword super. • super has two general forms: 1. It is used to invoke/ call the superclass’ constructor. 2. It is used to access a member of the superclass that has been hidden by a member of a subclass. 62 Prepared by THAPASWINI P S
  • 62.
    1. Using superto Call Superclass Constructors super(arg-list); Here, arg-list specifies any arguments needed by the constructor in the superclass. super( ) must always be the first statement executed inside a subclass’ constructor. Prepared by THAPASWINI P S 63
  • 63.
  • 64.
    class Box { doublewidth; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } void get() { System.out.println(width+" "+height+" "+depth); } } class BoxWeight extends Box { BoxWeight(double w, double h, double d) { super(w,h,d); } } class Main { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15); mybox1.get(); } } Prepared by THAPASWINI P S 65 Output: 10.0 20.0 15.0
  • 65.
    super( ) mustalways be the first statement executed inside a subclass constructor. Prepared by THAPASWINI P S 66
  • 66.
    class Box { doublewidth; double height; double depth; Box(double w, double h, double d) { width = w; height = h; depth = d; } } class BoxWeight extends Box { double weight; BoxWeight(double w, double h, double d, double m) { super(w,h,d); weight = m; } } class DemoBoxWeight { public static void main(String args[]) { BoxWeight mybox1 = new BoxWeight(10, 20, 15, 34.3); } } 67 Prepared by THAPASWINI P S
  • 67.
    A Second Usefor super • The second form of super always refers to the superclass of the subclass in which it is used. This usage has the following general form: super.member Here, member can be either a method or an instance variable. Prepared by THAPASWINI P S 68
  • 68.
    class A { inti; } class B extends A { int i; B(int a, int b) { super.i = a; i = b; } void show() { System.out.println("i in superclass: " + super.i); System.out.println("i in subclass: " + i); } } class UseSuper { public static void main(String args[]) { B subOb = new B(1, 2); subOb.show(); } } 69 Prepared by THAPASWINI P S
  • 69.
    Creating a MultilevelHierarchy(Multilevel Inheritance) Class X { public void methodX() { System.out.println("Class X method"); } } Class Y extends X { public void methodY() { System.out.println("class Y method"); } } Class Z extends Y { public void methodZ() { System.out.println("class Z method"); } } 70 Prepared by THAPASWINI P S Class Multilevel{ public static void main(String args[]) { Z obj = new Z(); obj.methodX(); obj.methodY(); obj.methodZ(); } }
  • 70.
    When Constructors AreCalled [VTU QP: Explain with example, when constructors are called in class hierarchy] class A { A() { System.out.println("Inside A's constructor."); } } class B extends A { B() { System.out.println("Inside B's constructor."); } } class C extends B { C() { System.out.println("Inside C's constructor."); } } 71 Prepared by THAPASWINI P S •In a class hierarchy, constructors are called in order of derivation, from super class to subclass. Output: Inside A’s constructor Inside B’s constructor Inside C’s constructor class CallingCons { public static void main(String args[]) { C obj = new C(); } }
  • 71.
    Method Overriding [VTU QP:Compare and contrast method overloading and method overriding with suitable example.] • In a class hierarchy, when a method in a subclass has the same name and type signature as a method in its superclass, then the method in the subclass is said to override the method in the superclass. • When an overridden method is called from within a subclass, it will always refer to the version of that method defined by the subclass. 72 Prepared by THAPASWINI P S
  • 72.
    class A { inti, j; A(int a, int b) { i = a; j = b; } void show() { System.out.println("i and j: " + i + " " + j); } } class B extendsA { 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(); } } 73 Prepared by THAPASWINI P S Output: k: 3
  • 73.
    class B extendsA { int k; B(int a, int b, int c) { super(a, b); k = c; } void show() { super.show(); // this calls A's show() System.out.println("k: " + k); } } 74 Prepared by THAPASWINI P S If we wish to access the superclass version of an overridden method, you can do so by using super.
  • 74.
    Method Overloading • Methodoverriding occurs only when the names and the type signatures of the two methods are identical. If they are not, then the two methods are simply overloaded. Prepared by THAPASWINI P S 75 class A { int i, j; A(int a, int b) { i = a; j = b; } // display i and j void show() { System.out.println("i and j: " + i + " " + j); } } // Create a subclass by extending class A. class B extends A { int k; B(int a, int b, int c) { super(a, b); k = c; } // overload show() void show(String msg) { System.out.println(msg + k); } } class Override { public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show("This is k: "); // this calls show() in B subOb.show(); // this calls show() in A } } Output: This is k: 3 i and j: 1 2
  • 75.
    Dynamic Method Dispatch •Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time, rather than compile time. • Dynamic method dispatch is important because this is how Java implements run-time polymorphism. • It is the type of the object being referred to determines which version of an overridden method will be executed. 76 Prepared by THAPASWINI P S
  • 76.
    class A { voidcallme() { System.out.println("Inside A's callme method"); } } class B extends A { // override callme() void callme() { System.out.println("Inside B's callme method"); } } class C extends A { // override callme() void callme() { System.out.println("Inside C's callme method"); } } Prepared by THAPASWINI P S 77 Output: Inside A’s callme method Inside B’s callme method Inside C’s callme method class Dispatch { public static void main(String args[]) { A a = new A(); // object of type A B b = new B(); // object of type B C c = new C(); // object of type C A r; // obtain a reference of type A 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 } }
  • 77.
    Abstract Classes • Anabstract class means that nobody can ever make a new instance of that class. • We can still use that abstract class as a declared reference type, for the purpose of polymorphism, but you don’t have to worry about somebody making objects of that type. The compiler guarantees it. 78 Prepared by THAPASWINI P S
  • 78.
    abstract class Animal { publicvoid roam() { System.out.println(" Animal Roam"); } } class Dog extends Animal { public void roam() { System.out.println(" Dog Roam"); } } public class Main { public static void main(String[] args) { Animal a=new Animal(); Dog c=new Dog(); c.roam(); } } Prepared by THAPASWINI P S 79
  • 79.
    Abstract methods • Sometimeswe will want to create a superclass that only defines a generalized form that will be shared by all of its subclasses, leaving it to each subclass to fill in the details. Such a class determines the nature of the methods that the subclasses must implement. • An abstract method has no body! • Only Prototype of the method inside class. Prepared by THAPASWINI P S 80
  • 80.
    // A Simpledemonstration of abstract. 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(); } } Prepared by THAPASWINI P S 81
  • 81.
    Using final withInheritance • The following are the two uses of final which apply to inheritance. i) Using final to Prevent Overriding • ii) Using final to Prevent Inheritance 82 Prepared by THAPASWINI P S
  • 82.
    i) Using finalto Prevent Overriding • To disallow a method from being overridden, specify final as a modifier at the start of its declaration. 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() { // ERROR! Can't override. System.out.println("Illegal!"); } } Prepared by THAPASWINI P S 83
  • 83.
    ii) Using finalto Prevent Inheritance final class A{ } // The following class is illegal. class B extends A { // ... } 84 Prepared by THAPASWINI P S
  • 84.