0% found this document useful (0 votes)
20 views

Unit 2

The document discusses object-oriented programming concepts in Java including method overloading, constructor overloading, passing objects as parameters, and call by value vs call by reference. It provides examples of overloading methods and constructors in a Box class to demonstrate how Java supports polymorphism. It also shows examples comparing how primitive types are passed by value while object references are passed by reference in Java.

Uploaded by

miniproj23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

Unit 2

The document discusses object-oriented programming concepts in Java including method overloading, constructor overloading, passing objects as parameters, and call by value vs call by reference. It provides examples of overloading methods and constructors in a Box class to demonstrate how Java supports polymorphism. It also shows examples comparing how primitive types are passed by value while object references are passed by reference in Java.

Uploaded by

miniproj23
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 69

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.

JAVA PROGRAMMING

UNIT - II
UNIT - 2
2

 Syllabus
A Closer Look at Methods and Classes: Overloading
Methods, Overloading Constructors, Using Objects as
Parameters, A Closer Look at Argument Passing,
Returning Objects, Recursion, Introducing Access
Control, understanding static, introducing final,
Introducing Nested and Inner Classes, Exploring the
String Class, Using Command-Line Arguments.
Inheritance: Inheritance Basics, Using super, Creating
a Multilevel Hierarchy, When Constructors Are
Executed, Method Overriding.
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Overloading Methods
3

 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. 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 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.
 Thus, 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.
 When Java encounters a call to an overloaded method, it simply executes
the version of the
Dr Yogish method
H K, whose
Professor, Dept. parameters
of ISE, match the arguments used in
RIT, Bengaluru -54.
the call.
Overloading Methods …Example
4

class OverloadDemo {
void test() {
System.out.println("No parameters");
}
// Overload test for one integer parameter.
void test(int a) {
System.out.println("a: " + a);
}
// Overload test for two integer parameters.
void test(int a, int b) {
System.out.println("a and b: " + a + " " + b);
}
// overload test for a double parameter
void test(double a) {
System.out.println("double a: " + a);
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Overloading Methods …Example
5

class Overload {
public static void main(String args[]) {
OverloadDemo ob = new OverloadDemo();
double result;
ob.test();
ob.test(10);
ob.test(10, 20);
ob.test(123.25);
}
}

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Overloading Constructors
6

 Like a normal methods, you can also overload


constructor methods.
 Example:

class Box {
double width, height, depth;
// constructor used when no dimensions specified
Box() {
width = -1; // use -1 to indicate
height = -1; // an uninitialized
depth = -1; // box
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Continue …
7

// constructor used when cube is created


Box(double len) {
width = height = depth = len;
}
// constructor used when all dimensions specified
Box(double w, double h, double d) {
width = w;
height = h;
depth = d;
}
// compute and return volume
double volume() {
return width * height * depth;
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Continue …
8

class OverloadCons {
public static void main(String args[]) {
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using Objects as Parameters
9

 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.
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if obj is equal to the invoking object
boolean equals(Test obj) {
if(a == obj.a && b == obj.b)
return true;
else
return false;
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using Objects as Parameters …
10

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));
}
}
This program generates the following output:
ob1 == ob2: true
ob1 == ob3: false
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
A Closer Look at Argument Passing
11

 There are two ways that a computer language can pass


an argument to a function or method.
 The first way is call-by-value. This approach copies
the value of an argument into the formal parameter of
the method. Therefore, changes made to the parameter
of the method have no effect on the argument.
 The second way an argument can be passed is call-by-
reference. In this approach, a reference to an argument
(not the value of the argument) is passed to the
parameter. Inside the method, this reference is used to
access the actual argument specified in the call. This
means that changes made to the parameter will affect
the argument used to call the method.
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Call by value …example
12
 In Java, when you pass a primitive type to a method, it is passed by value. Thus, what occurs to the
parameter that receives the argument has no effect outside the method.
class Test {
void fun(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.fun(a, b);
System.out.println("a and b after call: " + a + " " + b);
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Call by value …example…
13

The output from this program is shown here:


a and b before call: 15 20
a and b after call: 15 20

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Call by reference …example…
14

 When you pass an object to a method, the situation


changes dramatically, because objects are passed by
what is effectively call-by-reference.
 Keep in mind that when you create a variable of a class
type, you are only creating a reference to an object.
Thus, when you pass this reference to a method, the
parameter that receives it will refer to the same object
as that referred to by the argument. This effectively
means that objects are passed to methods by use of call-
by-reference.
 Changes to the object inside the method do affect the
object Drused asK, Professor,
Yogish H an argument.
Dept. of ISE, RIT, Bengaluru -54.
Call by reference …example…
15

class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// pass an object
void fun(Test obj) {
obj.a *= 2;
obj.b /= 2;
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Call by reference …example…
16

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.fun(ob);
System.out.println("ob.a and ob.b after call: " + ob.a + " " + ob.b);
}
}
This program generates the following output:
ob.a and ob.b before call: 15 20
ob.a and ob.b after
Dr Yogish H K, call:
Professor,30
Dept.10
of ISE, RIT, Bengaluru -54.
Recursion
17

 Java supports recursion. Recursion is the process of


defining something in terms of itself.
 As it relates to Java programming, recursion is the
attribute that allows a method to call itself.
 A method that calls itself is said to be recursive.

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Recursion …example
18

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 obj = new Factorial();
System.out.println("Factorial of 3 is " + ob.fact(3));
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Introducing Access Control
19

 As you know, encapsulation links data with the code that manipulates it.
However, encapsulation provides another important attribute: access control.
 Through encapsulation, you can control what parts of a program can access
the members of a class. By controlling access, you can prevent misuse.
 Java’s access specifiers are public, private, and protected. Java also defines a
default access level. protected applies only when inheritance is involved.
 When a member of a class is modified by the public specifier, then that
member can be accessed by any other code. When a member of a class is
specified as private, then that member can only be accessed by other members
of its class.
 Now you can understand why main( ) has always been preceded by the public
specifier. It is called by code that is outside the program—that is, by the Java
run-time system. When no access specifier is used, then by default the
member of a class is public within its own package, but cannot be accessed
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
outside of its package.
Introducing Access Control …
20

class Test {
int a; // default access
public int b; // public access
private int c; // private access
// methods to access c
void setc(int i) { // set c's value
c = i;
}
int getc() { // get c's value
return c;
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Introducing Access Control …
21

class AccessTest {
public static void main(String args[]) {
Test ob = new Test();
ob.a = 10; // These are OK, a and b may be accessed directly
ob.b = 20;
// This is not OK and will cause an error
// ob.c = 100; // Error! You must access c through its methods
ob.setc(100); // OK
System.out.println("a, b, and c: " + ob.a + " " + ob.b + " " + ob.getc());
}
}

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Static Variables and Methods
22

 Static Variables : The static keyword is used to


create variables that will exist independently of any
instances created for the class. Only one copy of the
static variable exists regardless of the number of
instances of the class. Static variables are also
known as class variables. Local variables cannot be
declared as static.

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Static Variables and Methods
23

 Static Methods
• The static keyword is used to create methods that
will exist independently of any instances created for
the class.
• 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. (The
keyword super
Dr Yogish H relates
K, Professor, toRIT,inheritance)
Dept. of ISE, Bengaluru -54.
Example: shows a class that has a static method, some static
variables, and a static initialization block:
24

class UseStatic {
static int a = 3;
static int b;
static void fun(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[]) {
fun(42);
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Continue…
25

As soon as the UseStatic class is loaded, all of the static statements are
run.
First, a is set to 3,
then the static block executes, which prints a message and then initializes
b to a*4 or 12.
Then main( ) is called, which calls meth( ), passing 42 to x. The three
println( ) statements refer to the two static variables a and b, as well as to
the local variable x.

Here is the output of the program:


Static block initialized.
x = 42
a=3
b = 12 Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Continue…
26

 Outside of the class in which they 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.
 For example, if you wish to call a static method from outside its
class, you can do so using the following general form:
classname.method( ) ;
 Here, classname is the name of the class in which the static
method is declared.

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Continue… Example
27

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);
}
}
Here is the output of this program:
a = 42
b = 99 Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Introducing final
28

 A variable can be declared as final.


 Doing so prevents its contents from being modified.
 You must initialize a final variable when it is declared.
For example:
 final int SIZE= 10;
 final double PI= 3.14;
 final int QUIT = 5;
 Subsequent parts of your program can now use SIZE,
PI etc.,

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Introducing Nested and Inner Classes
29

 Defining a class within another class is known as


nested class.
 The scope of a nested class is bounded by the
scope of its enclosing class.
 Thus, if class B is defined within class A, then B
does not exist independently of A.
 an inner class has access to all of the members of
its enclosing class, but the reverse is not true.
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Introducing Nested and Inner Classes …
30

 Syntax :Here the class Outer is the outer class


and the class Inner is the nested class.
class Outer{
class Inner{
}
}
 To access the inner class, create an object of the
outer class, and then create an object of the inner
class:Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Introducing Nested and Inner Classes …
31

 There are two types of nested classes:

 Static - These are the static members of a class.

 Non-Static -These are the non-static members of a class.

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Example - illustrate to define and use an inner class. The class
named Outer has one instance variable named o_x, and defines one
inner class called Inner.
32

class Outer {
int o_x = 10;
class Inner {
int i_y = 5;
}
}
class Main {
public static void main(String[] args) {
Outer Outerob = new Outer();
Outer.Inner Innerob = Outerob.new Inner();
System.out.println(Innerob.i_y + Outerob.o_x);
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
}
Static Inner Class : An inner class can also be static, which
means that you can access it without creating an object of the outer
class.
33

class Outer {
int o_x = 10;
static class Inner {
int i_y = 5;
}
}
class Main {
public static void main(String[] args) {
Outer Outerob = new Outer();
//Outer.Inner Innerob = Outerob.new Inner();
Outer.Inner Innerob = new Outer.Inner();
System.out.println(Innerob.i_y + Outerob.o_x);
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Exploring the String Class
34

 Strings, which are widely used in Java programming,


are a sequence of characters. In Java strings are
treated as objects.
 The Java provides the String class to create and
manipulate strings.
 String is probably the most commonly used class in
Java’s class library.

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Exploring the String Class ..
35

 The first thing to understand about strings is that


every string you create is actually an object of type
String. Even string constants are actually String
objects.
 For example, in the statement
System.out.println("This is a String, too");
 the string “This is a String, too” is a String constant.

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Exploring the String Class ..
36

 The second thing to understand about strings is that


objects of type String are immutable;
 Once a String object is created, its contents cannot be
altered. While this may seem like a serious restriction, it
is not, for two reasons:
• If you need to change a string, you 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 Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Exploring the String Class ..
37

 Strings can be constructed in a variety of ways. The


easiest is to use a statement like this:
String myString = "this is a test";
 Once you have created a String object, you can use it
anywhere that a string is allowed.
 For example, this statement displays myString:
System.out.println(myString);
 Java defines one operator for String objects: +. It is used
to concatenate two strings. For example, this statement
String myString = "I" + " like " + "Java.";
 Results in myString containing “I like Java.”
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Example
38
class StringDemo {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1 + " and " + strOb2;
System.out.println(strOb1);
System.out.println(strOb2);
System.out.println(strOb3);
}
}
The output produced by this program is shown here:
First String
Second String
First String and Second String
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
String class - methods
39

 equals( ) - two strings for equality


 length( ) - obtain the length of a string
 charAt( ) - obtain the character at a specified
index
 The general forms of these three methods are:
 boolean equals(String object) ;
 int length( ) ;
 char charAt(int index);

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Example
40

class StringDemo2 {
public static void main(String args[]) {
String strOb1 = "First String";
String strOb2 = "Second String";
String strOb3 = strOb1;
System.out.println("Length of strOb1: " + strOb1.length());
System.out.println("Char at index 3 in strOb1: " + strOb1.charAt(3));
if(strOb1.equals(strOb2))
System.out.println("strOb1 == strOb2");
else
System.out.println("strOb1 != strOb2");
if(strOb1.equals(strOb3))
System.out.println("strOb1 == strOb3");
else
System.out.println("strOb1 != strOb3");
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
}
Output
41

 This program generates the following output:


Length of strOb1: 12
Char at index 3 in strOb1: s
strOb1 != strOb2
strOb1 == strOb3

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Using Command-Line Arguments
42

 Sometimes you will want to pass information into a


program when you run it. This is accomplished by
passing command-line arguments to main( ).
 A command-line argument is the information that
directly follows the program’s name on the command
line when it is executed.
 Command-line arguments are stored as strings in a
String array passed to the args parameter of main( ).
 The first command-line argument is stored at args[0],
the second at args[1], and so on.
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Display all command-line arguments.
43

class CommandLine {
public static void main(String args[]) {
for(int i=0; i<args.length; i++)
System.out.println("args[" + i + "]: " + args[i]);
}
}
 java CommandLine this is a test 100 -1

args[0]: this
args[1]: is
args[2]: a
args[3]: test
args[4]: 100
args[5]: -1 Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Inheritance
44

 Inheritance can be defined as the process where


one class acquires the properties (methods and
fields) of another class.
 The class which inherits the properties of other is
known as subclass (derived class, child class)
 the class whose properties are inherited is known
as superclass (base class, parent class).
 Therefore, a subclass is a specialized version of a
superclass. It inherits all of the instance variables and
methods defined by the superclass and adds its own,
unique elements.
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Inheritance Basics
45

 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:
class subclass-name extends superclass-name {
// body of class
}

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Example - The following program creates a
superclass called A and a subclass called B.
46

class A { // Create a superclass.


int i;
void showi() {
System.out.println("i " + i );
}
}
class B extends A { // Create a subclass by extending class A.
int j;
void showj() {
System.out.println(“j: " + j);
}
void sum() {
System.out.println("i+j: " + (i+j));
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Example - The following program creates a
superclass called A and a subclass called B. ….
47
class SimpleInheritance {
public static void main(String args[]) {
B subOb = new B();
/* The subclass has access to all public members of its superclass. */
subOb.i = 7; subOb.j = 8;
System.out.println("Contents of subOb: ");
subOb.showi();
subOb.showj();
System.out.println();
System.out.println("Sum of I and j in subOb:");
subOb.sum();
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Member Access and Inheritance
48

 a subclass includes all of the members of its


superclass, it cannot access those members of the
superclass that have been declared as private.
 Ie. A class member that has been declared as
private will remain private to its class. It is not
accessible by any code outside its class, including
subclasses.

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Member Access and Inheritance … Example
49

// Create a superclass.
class A {
int i; // public by default
private int k; // private to A
void setij(int x, int y) {
i = x;
k = y;
}
}
// A’s k is not accessible here.
class B extends A {
int total;
void sum() {
total = i + k; // ERROR, k is not accessible here
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
}
Using super
50

 super has 2 uses.


 1. Used for calling the superclass’ constructor.
super(arg-list);
 2. Used to access a member of the superclass that

has been hidden by a member of a subclass.


super.member ;
 Here, member can be either a method or an instance
variable.
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super
51

 Example1: Used to call the superclass’ constructor

class A { // Create a superclass.


int i;
A(int a){
i=a;
}
void showi() {
System.out.println("i " + i );
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super ….
52

class B extends A {
int j;
B(int b1,int b2 {
super(b1);
j=b2;
}
void showj() {
System.out.println(“j: " + j);
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super ….
53

class SimpleInheritance {
public static void main(String args[]) {
B subOb = new B(5,10);
System.out.println("Contents of subOb: ");
subOb.showi();
subOb.showj();
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super - member names of a subclass hide
members by the same name in the superclass
54

 The second is used to access a member of the


superclass that has been hidden by a member of
a subclass. super.member;

// Using super to overcome name hiding.


class A {
int i;
}

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Using super - member names of a subclass hide
members by the same name in the superclass ….
55

// Create a subclass by extending class A.


class B extends A {
int i; // this i hides the i in A
B(int b1, int b2) {
super.i = b1; // i in A
i = b2; // i in B
}
void show() {
System.out.println("i in superclass: " + super.i);
System.out.println("i in subclass: " + i);
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super …
56

class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}
This program displays the following output:
i in superclass: 1
i in subclass: 2
Although the instance variable i in B hides the i in A, super
allows access to the i defined in the superclass. As you will see,
super can also be used to call methods that are hidden by a
subclass Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super …
57

 Super can also be used to call methods that are


hidden by a subclass.
 // Using super to overcome method hiding.
class A {
int i;
void show() {
System.out.println("i in superclass: " + i);
}
}

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Using super …
58

class B extends A {
int j ;
B(int b1, int b2) {
i=b1;
j = b2;
}
void show() {
super.show();
System.out.println("j in subclass: " + j);
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Using super …
59

class UseSuper {
public static void main(String args[]) {
B subOb = new B(1, 2);
subOb.show();
}
}

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


Creating a Multilevel Hierarchy
60

 We have been using simple class hierarchies that


consist of only a superclass and a subclass.
 However, you can build hierarchies that contain as
many layers of inheritance as you like.
 As mentioned, it is perfectly acceptable to use a
subclass as a superclass of another.
 For example, given three classes called A, B, and C, C
can be a subclass of B, which is a subclass of A.
 When this type of situation occurs, each subclass
inherits all of the traits found in all of its super classes.
In this case, C inherits all aspects of B and A.
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Example
61

class A { int i;
void showi() {
System.out.println("i " + i );
}
}
class B extends A { int j;
void showj() {
System.out.println(“j: " + j);
}
}
class C extends B { int k;
void showk() {
System.out.println("k: " + k);
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Example
62

void sum() {
System.out.println("i+j+k: " + (i+j+k));
}
}
class MultilevelInheritance {
public static void main(String args[]) {
C subOb = new C();
subOb.i = 7; subOb.j = 8; subOb.k =9 ;
System.out.println("Contents of subOb: ");
subOb.showi(); subOb.showj(); subOb.showk();
System.out.println("Sum of i ,j and k in subOb:");
subOb.sum();
}
} Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
When Constructors are Called
63

 In a class hierarchy, constructors are called in order


of derivation, from superclass to subclass.

 For example, given a subclass called B and a


superclass called A, is A’s constructor called before
B’s.

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.


When Constructors Are Called ..Example
64

class A {
A() {
System.out.println(" A's constructor.");
}
}
class B extends A {
B() {
System.out.println("B's constructor.");
}
}
class C extends B {
C() {
System.out.println("C's constructor.");
}
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
When Constructors Are Called ..Example
65

class CallingCons {
public static void main(String args[]) {
C ob = new C();
}
}
Output:
A’s constructor
B’s constructor
C’s constructor
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Method Overriding
66

 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 its 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 Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
Method Overriding…EXAMPLE
67

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;
}
Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.
….
68

// display k – this overrides show() in A


void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) {
B subOb = new B(1, 2, 3);
subOb.show(); // this calls show() in B
}
}
Output : k:3
Method overriding occurs only when the names and the type signatures of the two
Dr Yogish H K,
methods are identical. If Professor,
they areDept.
not,ofthen
ISE, RIT,
theBengaluru -54.
two methods are simply overloaded.
69 THANK YOU

Dr Yogish H K, Professor, Dept. of ISE, RIT, Bengaluru -54.

You might also like