Java Programming
Unit – 2
Classes, Inheritance, Polymorphism
Dr. Y. J. Nagendra Kumar
Professor of IT
Dean Technology and Innovation Cell - GRIET
TABLE OF CONTENTS
01 Classes and Objects
02 Strings
03 Inheritance
04 Polymorphism
Dr. Y. J. Nagendra Kumar - 2
Classes and Objects
Dr. Y. J. Nagendra Kumar - 3
Classes
A class is a template for an object, and an object is an instance 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
}
} Dr. Y. J. Nagendra Kumar - 4
Classes contd.,
• The data, or variables, defined within a class are called instance
variables.
• The code is contained within methods.
• Collectively, the methods and variables defined within a class are called
members of the class.
• Variables defined within a class are called instance variables because
each instance of the Class contains its own copy of these variables.
Dr. Y. J. Nagendra Kumar - 5
Declaring Objects
• Objects of a class is a two-step process.
• 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.
• Second, we must acquire an actual, physical copy of the object and
assign it to that variable. We can do this using the new operator.
• The new operator dynamically allocates (that is, allocates at run
time) memory for an object
Dr. Y. J. Nagendra Kumar - 6
Declaring Objects Contd.,
• Box mybox; // declare reference to object
• After this line executes, mybox contains the value null.
• mybox = new Box(); // allocate a Box object
• This line allocates an actual object and assigns a
reference to it to mybox.
• We can combine the above statements into a singe one as
follows:
• Box mybox = new Box();
Dr. Y. J. Nagendra Kumar - 7
Declaring Objects Contd.,
A class is a logical construct. An object has physical reality.
Dr. Y. J. Nagendra Kumar - 8
Declaring Objects Contd.,
class Box [Link] = 10;
{ [Link] = 20;
double width; [Link] = 15;
double height;
double depth; vol = [Link] * [Link] *
} [Link];
class BoxDemo
{ public static void main(String args[]) [Link]("Volume is " + vol);
{ Box mybox = new Box(); }
double vol; }
Dr. Y. J. Nagendra Kumar - 9
Assigning Object Reference Variables
Box b1 = new Box();
Box b2 = b1;
• b1 and b2 will both refer to the same object.
• The assignment of b1 to b2 did not allocate any memory.
• It simply makes b2 refer to the same object as does b1.
• Thus, any changes made to the object through b2 will
affect the object to which b1 is referring
Dr. Y. J. Nagendra Kumar - 10
Assigning Object Reference Variables contd.,
Box b1 = new Box();
Box b2 = b1;
// ...
b1 = null;
Here, b1 has been set to null, but b2 still points to the original object.
Dr. Y. J. Nagendra Kumar - 11
Introducing Methods
• Classes usually consist of two things:
instance variables and
methods.
• This is the general form of a method:
type name(parameter-list) {
// body of method
}
• Here, type specifies the type of data returned by the method.
This can be any valid type, including class types
Dr. Y. J. Nagendra Kumar - 12
Introducing Methods Contd.,
• If the method does not return a value, its return type must
be void.
• The name of the method is specified by name. This can be
any legal identifier.
• The parameter-list is a sequence of type and identifier
pairs separated by commas.
• return value;
• Here, value is the value returned.
Dr. Y. J. Nagendra Kumar - 13
Introducing Methods Example
class Box class BoxDemo1
{ { public static void main(String args[])
double width; { Box mybox1 = new Box();
double vol;
double height;
[Link] = 10;
double depth;
[Link] = 20;
double volume() [Link] = 15;
{ vol = [Link]();
return width * height * depth; [Link]("Volume is " + vol);
} }
} }
Dr. Y. J. Nagendra Kumar - 14
Adding a Method that takes parameters
class Box class BoxDemo2
{ double width; { public static void main(String args[])
double height; { Box mybox1 = new Box();
double depth; double vol;
void set(double w, double h, double d) [Link](20,30,40);
{ width=w; height=h; depth=d; } vol = [Link]();
double volume() [Link]("Volume is " + vol);
{ return width * height * depth; }
} }
}
Dr. Y. J. Nagendra Kumar - 15
Constructors
• It can be tedious to initialize all of the variables in a class each time
an instance is created.
• Even when we add convenience functions like set( )
• 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
Dr. Y. J. Nagendra Kumar - 16
Constructors contd.,
• The constructor is automatically called immediately after the object is
created.
• Constructors look a little strange because they have no return type, not
even void.
• This is because the implicit return type of a class’ constructor is the class
type itself.
• We can construct Box objects of various dimensions.
• The easy solution is to add parameters to the constructor. It is called
“Parameterized Constructors”.
Dr. Y. J. Nagendra Kumar - 17
Parameterized Constructors Example
class Box class Constructor
{ double width; { public static void main(String args[])
double height; {
double depth; Box mybox1 = new Box(20,30,40);
Box(double w,double h,double d) double vol;
{ width=w; height=h; depth=d; } vol = [Link]();
double volume() [Link]("Volume is " + vol);
{ return width * height * depth; }
} }
}
Dr. Y. J. Nagendra Kumar - 18
The this Keyword
• Sometimes a method will need to refer to the object that
invoked it.
• To allow this, Java defines the this keyword.
• this can be used inside any method to refer to the current
object.
• That is, this is always a reference to the object on which the
method was invoked.
Dr. Y. J. Nagendra Kumar - 19
The this Keyword
class Box double volume()
{ double width; { return width * height * depth;
double height; }
}
double depth;
class Constructor
{ public static void main(String args[])
Box(double width, double height, { Box mybox1 = new Box(20,30,40);
double depth) double vol;
{ [Link]=width; vol = [Link]();
[Link]=height; [Link]("Volume is " + vol);
[Link]=depth; }
} }
Dr. Y. J. Nagendra Kumar - 20
Garbage Collection
• Since objects are dynamically allocated by using the new operator
• When objects are destroyed and the memory released is used for later
reallocation.
• In some languages, such as C++, dynamically allocated objects must be
manually released by use of a delete operator.
• Java takes a different approach; it handles de allocation for us
automatically.
• The technique that accomplishes this is called garbage collection.
Dr. Y. J. Nagendra Kumar - 21
The finalize( ) Method
• Sometimes an object will need to perform some action when it is
destroyed.
• For example, if an object is holding some non-Java resource such as a file
handle or network connections, data base connections, then we might
want to make sure these resources are freed before an object is destroyed.
• To handle such situations, Java provides a mechanism called finalization.
• To add a finalizer to a class, you simply define the finalize( ) method.
Dr. Y. J. Nagendra Kumar - 22
The finalize( ) Method Contd.,
• The Java run time calls that method whenever it is about to recycle an
object of that class.
• Inside the finalize( ) method, you will specify those actions that must be
performed before an object is destroyed.
• The garbage collector runs periodically, checking for objects that are no
longer referenced. protected void finalize( )
{
// finalization code here
}
Dr. Y. J. Nagendra Kumar - 23
Method Overloading
• In Java it is possible to define two or more methods within the same
class that share the same name, as long as their parameter declarations
are different. The methods are said to be overloaded, and the process is
referred to as method overloading.
Dr. Y. J. Nagendra Kumar - 24
Method Overloading
• Method overloading is one of the ways that Java implements
Polymorphism.
• When an overloaded method is invoked, Java uses the type and/or
number of arguments as its guide to determine which version of the
overloaded method to actually call.
• overloaded methods must differ in the type and/or number of their
parameters.
• While overloaded methods may have different return types, the return
type alone is insufficient to distinguish two versions of a method.
Dr. Y. J. Nagendra Kumar - 25
Automatic Type Conversion
• When an overloaded method is called, Java looks for a match
between the arguments used to call the method and the method’s
parameters.
• However, this match need not always be exact. In some cases Java’s
automatic type conversions can play a role in overload resolution.
Dr. Y. J. Nagendra Kumar - 26
Method Overloading
Method Example
Overloading Example
class overloading class methodoverloading
{ void show() {
{[Link]("No arguments"); public static void main(String ar[])
} {
void show(int x,int y) overloading m=new overloading();
{ [Link](“2 arguments"+x+y); [Link]();
} [Link](33,44);
void show(double x) [Link](3.14);
{ [Link](22);
[Link]("one argument :"+x); }
} }
} Dr. Y. J. Nagendra Kumar - 27
Overloading Constructors
• In addition to overloading normal methods, we can also overload
constructor methods.
Using Objects as Parameters
• 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.
Dr. Y. J. Nagendra Kumar - 28
Overloading Constructors Example
class rect class rectarea
{ double l,b; { public static void main(String ar[])
rect() {
{ l=10;b=20; } rect r1=new rect();
rect(int x,int y) rect r2=new rect(22,33);
{ l=x; b=y; } rect r3=new rect(r2);
rect(rect n) rect r4=new rect(55.6);
{ l=n.l;
b=n.b; } [Link]();
rect(double x) [Link]();
{ l=b=x; } [Link]();
void area() [Link]();
{ [Link]("Area :"+l*b); } }
} Dr. Y. J. Nagendra}Kumar - 29
Returning Objects Example
● A method can return any type of data, including class types that we create.
class Test class retobjects
{ {
int a; public static void main(String args[])
{
Test(int i) Test ob1 = new Test(5);
{ Test ob2;
a=i;
} ob2=[Link]();
Test incr() [Link]("ob1.a : "+ob1.a);
{ [Link]("ob2.a : "+ob2.a);
Test temp=new Test(a+10);
return temp; }
} }
}
Dr. Y. J. Nagendra Kumar - 30
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.
• We can declare both methods and variables to be static.
• The most common example of a static member is main( ). main( ) is
declared as static because it must be called before any objects exist.
• Instance variables declared as static are, essentially, global
variables.
Dr. Y. J. Nagendra Kumar - 31
Dr. Y. J. Nagendra Kumar - 32
Static
• All instances of the class share the same static variable.
– Ex: static int a = 3;
• Methods declared as static 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
– Syntax: [Link]( )
Ex: static void callme()
{ [Link]("a = " + a); }
Dr. Y. J. Nagendra Kumar - 33
Static Example
class StaticDemo class statics
{ {
static int a = 42; public static void main(String args[])
static int b = 99; {
[Link]();
static void callme()
{ [Link]("b = " + StaticDemo.b);
[Link]("a = " + a); }
} }
}
Dr. Y. J. Nagendra Kumar - 34
final
• “final” keyword prevents its contents from being modified. This means
that we must initialize a final variable when it is declared.
• 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.
Ex: final int x=22;
Dr. Y. J. Nagendra Kumar - 35
Access specifiers
• A member can be accessed is determined by the access specifier.
• Java’s access specifiers are public, private, and protected. Java also defines a
default access level.
• public: member can be accessed by any other code
• private: member can only be accessed by other members of its class
• Protected: applies only when inheritance is involved
• defalut: When no access specifier is used, then by default the member of a
class is public within its own package, but cannot be accessed outside of its
package.
Dr. Y. J. Nagendra Kumar - 36
Access Specifiers Example
class Test class Access
{ { public static void main(String args[])
int a; // default access { Test ob = new Test();
public int b; // public access ob.a = 10;
private int c; // private access ob.b = 20;
// methods to access c // ob.c = 100; // Error!
void setc(int i) [Link](100); // OK
{ c = I; } [Link]("a, b, and c: " + ob.a +
int getc() " " +ob.b + " " + [Link]());
{ return c; } }
} }
Dr. Y. J. Nagendra Kumar - 37
Nested Classes
• Nested Class: define a class within another class
• The scope of a nested class is bounded by the scope of its enclosing
class.
• Ex: if class B is defined within class A, then B is known to A, but not
outside of A.
• A nested class has access to the members, including private
members, of the class in which it is nested. However, the enclosing
class does not have access to the members of the nested class.
Dr. Y. J. Nagendra Kumar - 38
Static Nested Classes
• There are two types of nested classes:
• static
• non-static.
• A static nested class is one which has the static modifier applied.
Because it is static, it must access the members of its enclosing class
through an object.
• That is, it cannot refer to members of its enclosing class directly.
Because of this restriction, static nested classes are seldom used.
Dr. Y. J. Nagendra Kumar - 39
Static Nested Classes Example
class Outer class Innerrr
{ int outer_x = 100; {
void test() public static void main(String args[])
{ Inner in=new Inner(); {
[Link](); Outer outer = new Outer();
} [Link]();
static class Inner }
{ void display() }
{ Outer out=new Outer();
[Link]("display: outer_x = " +
out.outer_x);
}
}}
Dr. Y. J. Nagendra Kumar - 40
Non Static Nested Classes (Inner Classes)
• An inner class is a non-static nested class.
• It has access to all of the variables and methods of its
outer class and may refer to them directly.
Dr. Y. J. Nagendra Kumar - 41
Inner Classes Example
class Outer class InnerClass
{ int outer_x = 100; {
void test() public static void main(String args[])
{ Inner in=new Inner(); {
[Link](); Outer outer = new Outer();
} [Link]();
class Inner }
{ void display() }
{
[Link]("display: outer_x = " + outer_x);
}
}
}
Dr. Y. J. Nagendra Kumar - 42
Strings
Dr. Y. J. Nagendra Kumar - 43
Strings
• String constants are actually String objects
• Strings are immutable; once a String object is created, its contents
cannot be altered.
• If we need to change a string, we can always create a new one that
contains the modifications.
• Java defines a peer class of String, called StringBuffer, which allows
strings to be altered.
Dr. Y. J. Nagendra Kumar - 44
String Methods
• Java defines one operator for String objects is +. It is used to
concatenate two strings.
• For ex: String myString = "I" + " like " + "Java.";
• boolean equals(String object) → test two strings for equality
• int length( ) → obtain the length of a string
• char charAt(int index)→ obtain the character at a specified index
within a string.
Dr. Y. J. Nagendra Kumar - 45
String Methods Example
class StringMethods if([Link](s2))
{ [Link]("s1 == s2");
public static void main(String args[]) else
{ [Link]("s1 != s2");
String s1 = "Pulse";
String s2 = "AnnualDay"; if([Link](s3))
String s3 = s1; [Link]("s1 == s3");
else
[Link]("Length of strOb1: " +[Link]()); [Link]("s1 != s3");
}
[Link]("Char at index 3 in strOb1: " }
+[Link](3));
Dr. Y. J. Nagendra Kumar - 46
String Buffer
• String represents fixed length, immutable character sequence.
• String Buffer represents extensible character sequence
• In String Buffer object, we can insert or append substrings at any
position.
• Array of Strings:
• String s[]={“IT”, “CSE”,”MCA”};
Dr. Y. J. Nagendra Kumar - 47
String Buffer Example
class StringBuf
{
public static void main(String a[])
{
StringBuffer sb=new StringBuffer("Happy Pongal");
[Link]("Length :"+[Link]());
[Link]("Capacity :"+[Link]());
[Link](6,"Bogi, ");
[Link](sb);
[Link](" and Kanuma");
[Link](sb);
}
}
Dr. Y. J. Nagendra Kumar - 48
String Tokenizer
• The [Link] class allows you to break a string into tokens. It
is simple way to break string.
Constructor Description
creates StringTokenizer with specified
StringTokenizer(String str)
string.
StringTokenizer(String str, String creates StringTokenizer with specified
delim) string and delimeter.
Dr. Y. J. Nagendra Kumar - 49
Methods of String Tokenizer Class
• The 6 useful methods of StringTokenizer class are as follows:
Public method Description
boolean hasMoreTokens() checks if there is more tokens available.
returns the next token from the StringTokenizer
String nextToken()
object.
String nextToken(String delim) returns the next token based on the delimeter.
boolean hasMoreElements() same as hasMoreTokens() method.
Object nextElement() same as nextToken() but its return type is Object.
int countTokens() returns the total number of tokens.
Dr. Y. J. Nagendra Kumar - 50
String Tokenizer Example
import [Link];
import [Link];
public class Tokenizer1
{ public static void main(String[] args)
{ String s;
Scanner sc=new Scanner([Link]);
s=[Link]();
StringTokenizer st = new StringTokenizer(s);
//iterate through tokens
while([Link]())
[Link]([Link]());
}
} Dr. Y. J. Nagendra Kumar - 51
Inheritance
Dr. Y. J. Nagendra Kumar - 52
Inheritance
● The mechanism of deriving a new class from an old one is called
Inheritance.
● The old class is known as “base” or “super” or “parent” class.
● The new one is called the “derived” or “sub” or “child” class.
● The forms of Inheritance
○ Single
○ Multiple
○ Multi level
○ Hierarchical
○ Hybrid
Dr. Y. J. Nagendra Kumar - 53
Types of Inheritance
Dr. Y. J. Nagendra Kumar - 54
Single Inheritance
● Subclass inherits all of the instance variables and methods defined by the
super class and adds its own unique elements.
● To inherit a class we simply incorporate the definition of one class into
another by using the “extends” keyword.
● Syn:
class subclassname extends superclassname
{
//body
}
● Subclass cannot access those members of super class that have been declared as
“private”
Dr. Y. J. Nagendra Kumar - 55
Single Inheritance Example
class rect class box extends rect
{ double length; {
double breadth; double height;
rect() box(double l,double b,double h)
{ length=-1; breadth=-1; } { length=l;
rect(double l,double b) breadth=b;
{ height=h;
length=l; breadth=b; }
} void volume()
double area() {
{ [Link]("Volume :
return length*breadth; "+length*breadth*height);
} }
} }
Dr. Y. J. Nagendra Kumar - 56
Single Inheritance Example Contd.,
class inhert1
{
public static void main(String ar[])
{
rect r=new rect(20,10);
[Link]("Area : "+[Link]());
box b=new box(20,10,5);
[Link]();
}
}
Dr. Y. J. Nagendra Kumar - 57
● In the previous example, the constructor for box explicitly initializes
the length and breadth fields of rectangle. This duplicate code makes
the program inefficient.
● Java provides a solution to this problem. Whenever a subclass needs
to refer to its immediate superclass, it can do so by use of the
keyword “super”.
Dr. Y. J. Nagendra Kumar - 58
‘super’ forms
● super has two general forms.
○ The first calls the superclass’ constructor.
○ The second is used to access a member of the superclass
Dr. Y. J. Nagendra Kumar - 59
Using super to Call Superclass Constructors
● A subclass can call a constructor method defined by its superclass
by using the following form of super:
super(parameter-list);
● Here, parameter-list specifies any parameters needed by the
constructor in the superclass.
● super( ) must always be the first statement executed inside a
subclass’ constructor.
Dr. Y. J. Nagendra Kumar - 60
Super First form Example
class rect class box extends rect
{ double length; {
double breadth; double height;
rect() box()
{ length=-1; breadth=-1; } { super();
rect(double l,double b) height=-1; }
{ box(double l,double b,double h)
length=l; breadth=b; { super(l,b);
} height=h; }
double area() void volume()
{ {
return length*breadth; [Link]("Volume : “+length*breadth*height);
} }
} }
Dr. Y. J. Nagendra Kumar - 61
Super First form Example Contd.,
class inhert2
{
public static void main(String ar[])
{
rect r=new rect(20,10);
[Link]("Area : "+[Link]());
box b=new box(30,40,5);
[Link]();
}
}
Dr. Y. J. Nagendra Kumar - 62
A Second Use for super
• The second form of super acts like this, except that it always refers to
the superclass of the subclass in which it is used.
Syn: [Link]
• Here, member can be either a method or an instance variable.
• This second form of super is most applicable to situations in which
member names of a subclass hide members by the same name in the
superclass.
Dr. Y. J. Nagendra Kumar - 63
Super Second form Example
class A void display()
{ {
int i; [Link](" Super i : "+super.i);
} [Link](" Sub i : "+i);
}
class B extends A }
{ class inhert3
int i; {
public static void main(String ar[])
B(int a,int b) {
{ B sub=new B(20,30);
super.i=a; [Link]();
i=b; }
} }
Dr. Y. J. Nagendra Kumar - 64
Polymorphism
Dr. Y. J. Nagendra Kumar - 65
Polymorphism
• Polymorphism in Java is a concept by which we can perform a single
action in different ways.
• The word "poly" means many and "morphs" means forms. So
polymorphism means many forms.
Dr. Y. J. Nagendra Kumar - 66
Method Overloading
• In Java, it is possible to create methods that have the same name, but
different parameter lists and different definitions. This is called
“Method Overloading”.
• Method Overloading is used when objects are required to perform
similar tasks but using different input parameters. This process is
known as Polymorphism.
Dr. Y. J. Nagendra Kumar - 67
Method Overloading Example
class A void display(String s)
{ int i,j; { [Link](s+k);
A(int a, int b) }
{ i=a;j=b; } }
void display() class overload
{ {
[Link](" i and j "+i+" "+j); public static void main(String ar[])
} {
} B sub=new B(10,20,30);
class B extends A
{ int k; [Link](" this is :");
B(int a,int b,int c) [Link]();
{ super(a,b); }
k=c; } }
Dr. Y. J. Nagendra Kumar - 68
Method Overriding
• 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.
The version of the method defined by the superclass will be hidden.
Dr. Y. J. Nagendra Kumar - 69
Method Overriding Example
class A void display()
{ int i,j; {
A(int a, int b) [Link]("k: " + k);
{ i=a;j=b; } }
void display() }
{ class Override
[Link](" i and j "+i+" "+j); {
} public static void main(String args[])
} {
class B extends A B subOb = new B(1, 2, 3);
{ int k; [Link](); // this calls show() in B
B(int a,int b,int c) }
{ super(a,b); }
k=c; }
Dr. Y. J. Nagendra Kumar - 70
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 also known as run-time
polymorphism.
Dr. Y. J. Nagendra Kumar - 71
Dynamic Method Dispatch
● When an overridden method is called through a superclass reference,
Java determines which version of that method to execute based upon
the type of the object being referred to at the time the call occurs.
● Thus, this determination is made at run time. When different types of
objects are referred to, different versions of an overridden method will
be called.
Dr. Y. J. Nagendra Kumar - 72
Dynamic Method Dispatch Example
class draw class triangle extends draw
{ {
double d1,d2; triangle(double a,double b)
{
draw(double a, double b) super(a,b);
{ }
d1=a;d2=b;
} double area()
double area() {
{ [Link](" Inside Area for Triangle : ");
[Link](" Area is undefined"); return d1*d2/2; // base * height / 2
return 0; }
} }
}
Dr. Y. J. Nagendra Kumar - 73
Dynamic Method Dispatch Example contd.,
class rectangle extends draw class dynamic
{ { public static void main(String ar[])
rectangle(double a,double b) { draw d=new draw(10,20);
{ triangle t=new triangle(12,8);
super(a,b); rectangle r=new rectangle(6,4);
} draw ref;
ref=d;
double area() [Link]("Area is :"+[Link]());
{ ref=t;
[Link](" Inside Area for Rectangle : "); [Link]("Area is :"+[Link]());
return d1*d2; // length * breadth ref=r;
} [Link]("Area is :"+[Link]());
} }
}
Dr. Y. J. Nagendra Kumar - 74
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.
Dr. Y. J. Nagendra Kumar - 75
Final method Example
class A class finalkeyword
{ { public static void main(String ar[])
final void display() { A a=new A();
{ [Link](" Inside A "); [Link]();
} B b=new B();
} [Link](); }
class B extends A }
{ Output:
// Error cannot override becoz of final D:\>javac [Link]
void display() [Link]: display() in B cannot override
{ display() in A; overridden method is final
[Link](" Inside B "); void display() // Error cannot override becoz of
} final
} ^ 1 error
Dr. Y. J. Nagendra Kumar - 76
Using final to Prevent Inheritance
• Sometimes we will want to prevent a class from being inherited. To
do this, precede the class declaration with final.
• Declaring a class as final implicitly declares all of its methods as final,
too.
• It is illegal to declare a class as both abstract and final since an
abstract class is incomplete by itself and relies upon its subclasses to
provide complete implementations.
Dr. Y. J. Nagendra Kumar - 77
Final Class Example
final class A class finalclass
{ { public static void main(String ar[])
void display() { A a=new A();
{ [Link](" Inside A "); [Link]();
} B b=new B();
} [Link]();
class B extends A }
// Error cannot Inherit becoz of final }
{ Output:
void display() D:\>javac [Link]
{ [Link]: cannot inherit from final A
[Link](" Inside B "); class B extends A // Error cannot Inherit becoz of final
} ^ 1 error
}
Dr. Y. J. Nagendra Kumar - 78
Abstract Classes
Dr. Y. J. Nagendra Kumar - 79
Abstract Classes
• A superclass that declares the structure of a given abstraction
without providing a complete implementation of every method.
• 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.
• This situation can occur is when a superclass is unable to create a
meaningful implementation for a method.
Dr. Y. J. Nagendra Kumar - 80
Abstract Methods
• Java’s solution to this problem is the abstract method.
• To declare an abstract method, use this general form:
abstract type methodname(parameter-list);
*** no method body is present.
Dr. Y. J. Nagendra Kumar - 81
Abstract Classes
• Any class that contains one or more abstract methods must be
declared abstract.
• To declare a class abstract, simply use the abstract keyword in front
of the class keyword at the beginning of the class declaration.
• There can be no objects of an abstract class. That is, an abstract class
cannot be directly instantiated with the new operator.
• Such objects would be useless, because an abstract class is not fully
defined.
Dr. Y. J. Nagendra Kumar - 82
Abstract Classes
abstract class draw class triangle extends draw
{ {
double d1,d2; triangle(double a,double b)
draw(double a, double b) {
{ super(a,b);
d1=a;d2=b; }
} double area()
abstract double area(); {
} [Link](" Inside Area for Triangle : ");
return d1*d2/2; // base * height / 2
}
}
Dr. Y. J. Nagendra Kumar - 83
Abstract Classes
class rectangle extends draw class abstractclasses
{ { public static void main(String ar[])
rectangle(double a,double b) {
{ // draw d=new draw(10,20); is illegal
super(a,b); triangle t=new triangle(12,8);
} rectangle r=new rectangle(6,4);
draw ref;
double area()
{ ref=t;
[Link](" Inside Area for [Link]("Area is :"+[Link]());
Rectangle : "); ref=r;
return d1*d2; // length * breadth [Link]("Area is :"+[Link]());
} }
} }
Dr. Y. J. Nagendra Kumar - 84
Object Class
• There is one special class, Object, defined by Java.
• All other classes are subclasses of Object. That is, Object is a
superclass of all other classes.
Dr. Y. J. Nagendra Kumar - 85
End of Unit II