Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
89 views

Module - 2 Closer Look - Inheritance

This document discusses object oriented programming concepts in Java, specifically focusing on Chapter 1 which covers methods and classes. Some key points: 1) It describes how to control access to class members using access modifiers like private, public, protected, and default. 2) It explains how to pass objects as arguments to methods and the difference between call by value and call by reference. 3) Methods can return objects in addition to primitive types. 4) Method overloading allows multiple methods to have the same name but differ in parameters, allowing static polymorphism.

Uploaded by

Vijay V
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
89 views

Module - 2 Closer Look - Inheritance

This document discusses object oriented programming concepts in Java, specifically focusing on Chapter 1 which covers methods and classes. Some key points: 1) It describes how to control access to class members using access modifiers like private, public, protected, and default. 2) It explains how to pass objects as arguments to methods and the difference between call by value and call by reference. 3) Methods can return objects in addition to primitive types. 4) Method overloading allows multiple methods to have the same name but differ in parameters, allowing static polymorphism.

Uploaded by

Vijay V
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Object Oriented Programming with JAVA [20MCA22]

Module – 2:
Chapter – 1: A Closer Look at Methods and Classes

2.1 Controlling Access to Class Members


2.2 Pass Objects to Methods
2.3 How Arguments are passed
2.4 Returning Objects
2.5 Method Overloading
2.6 Overloading Constructors
2.7 Recursion
2.8 Understanding Static
2.9 Introducing Nested and Inner Classes
2.10 Varargs: Variable-Length Arguments
Chapter – 2: Inheritance
2.1 Inheritance Basic
2.2 Member Access and Inheritance
2.3 Constructors and Inheritance
2.4 Using super to Call Superclass constructors
2.5 Using super to Access Superclass Members
2.6 Creating a Multilevel Hierarchy
2.7 When are Constructors Executed
2.8 Superclass References and Subclass Objects
2.9 Method Overriding
2.10 Overridden Methods support polymorphism
2.11 Why Overridden Methods
2.12 Using Abstract Classes
2.13 Using final
2.14 The Object Class.

Prepared by
Mrs. Suma M G
Assistant Professor
Department of MCA
RNSIT
Bengaluru – 98.
JAVA Programming [20MCA22] Module-2
Chapter-1

A Closer Look at Methods and Classes

1.1 Controlling Access to Class Members:


Supports for encapsulation, the class provides 2 major benefits:
❖ Links data with the code that manipulates it.
❖ By which access to members can be controlled.
Restricting access to a class’s members is a fundamental part of object-oriented programming because it helps
prevent the misuse of an object that by using following access modifiers.
Table 1.1 : Access Specifiers
➢ private Same package Other Package
Modifiers Sub class Sub class
➢ public Same class Other class Other class
(Inheritance) (Inheritance)
➢ protected Private YES NO NO NO NO
➢ default Default YES YES YES NO NO
Public YES YES YES NO YES
Protected
YES YES YES YES YES
(Inheritance)

Note: If no access modifiers is used, the default access setting is assumed.


Example 1.1:
class Myclass{
int a; private int b;
public int c; protected int d;
void setValue(int x, int y, int u, int v){
a=x;b=y;c=u;d=v;
}
void getValue(){
System.out.println("a= "+a+ "b= " +b+ "c= " +c+ "d= " +d);
}
}
class AccessDemo{
public static void main(String[] args){
Myclass ob=new Myclass();
ob.a=10;
ob.c=30;
ob.d=40;
ob.setValue(100,200,300,400);
ob.getValue();
}
}

By, Suma M G, AP, MCA, RNSIT 1 | 27


JAVA Programming [20MCA22] Module-2
1.2 Pass Objects to Methods:
➢ Pass simple types as parameters to method, it is also possible to pass objects to methods.
➢ If want to compare all members of two objects for equality, then passing object to method is the best
possible way.
Example 1.2:
class Myclass{ class PassObject{
int a, b; public static void main(String[] args){
Myclass(int x, int y){ Myclass ob1=new Myclass(10,20);
a=x; b=y; Myclass ob2=new Myclass(10,20);
} Myclass ob3=new Myclass(2,5);
boolean getValue(Myclass o){ System.out.println("ob1 same as ob2:"
if((o.a==a) & (o.b==b)) + ob1.getValue(ob2));
return true; System.out.println("ob1 same as ob3:"
else + ob1.getValue(ob3));
return false; }
} }
}

1.3 How Arguments are Passed:


There are two ways of passing an argument to a method.
1. Call-by-value 2. Call-by-reference
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.
Example1.3:
class Exchange{ class CallByValue{
void change(int a, int b){ public static void main(String[] str){
a=a+10; int a=10, b=20;
b=b+10; Exchange ob=new Exchange();
} System.out.println("A and B before
} call " + a + " " +b);

ob.change(a,b);
System.out.println("A and B before
call " + a + " " +b);
}
}

Call-by-reference:
• A reference to an argument (instead the value) is passed to the parameter. The passed reference is used
to access the actual argument specified in the call.
• Objects are passed by default as call-by-reference.
• When you pass reference to a method, the parameter that receives it will refer to the same. Thus Changes
to the object inside the method do affect the object used as an argument.

By, Suma M G, AP, MCA, RNSIT 2 | 27


JAVA Programming [20MCA22] Module-2
Example 1.4:
class CallByReference{
class Exchange{ public static void main(String[] str){
int a=1,b=2; Exchange ob=new Exchange();
void change(Exchange o){ Exchange ob1=new Exchange();
o.a=o.a+10; o.b=o.b+10; System.out.println("A and B before
} call " + ob1.a + " " +ob1.b);
}
ob.change(ob1);
System.out.println("A and B before
call " + ob1.a + " " +ob1.b);
}
}
Note: “In Java, when you pass a primitive type to a method, it is passed by value and Objects are implicitly
passed by using call-by-reference.”

1.4 Returning Objects:


In Java, a method can return any type of data, including class types that you create.
Example1.5:
class Number{ class ReturnOb{
int n=10; public static void main(String[] args)
Number add(){ {
Number temp=new Number(); Number ob=new Number();
temp.n=n*n; Number ob2 = ob.add();
return temp;//returning object System.out.println("Result is:"
} +ob2.display());
int display(){ }
return n; }
}
}

1.5 Method Overloading:


Method Overloading is a way of defining two or more methods with same name but different forms. It is also
known as Static Polymorphism.
Rules:
❖ Argument lists must differ in one of the following.
i. Data type of parameters. ii. Number of parameters. iii. Sequence of Data type of
Example: Example: parameters.
int sum(int); void show(int, int); Example:
float sum(float); void show(int); void show(int, float);
double sum(double); void show(int,int,int); void show(double, int);

❖ Return type has no effect on overloading.


void show(int, float);
int show(int, float);

By, Suma M G, AP, MCA, RNSIT 3 | 27


JAVA Programming [20MCA22] Module-2
Example 1.6:
class Overload{
void show(){
System.out.println("Overloading with no parameter");
}
void show(int a){
System.out.println("Overloading with a parameter " +a);
}
void show(int a, int b){
System.out.println("Overloading with 2 parameter " + a
+ " " + b );
}
void show(double a, double b){
System.out.println("Overloading with 2 different type "
+ a + " " + b );
}
}
class MethodOver{
public static void main(String[] args){
Overload o=new Overload();
o.show(); o.show(10);
o.show(10, 20); o.show(5.15, 6.15);
}
}

1.6 Overloading Constructors:


Like methods, constructors can also be overloaded. It is also known as Static Polymorphism.
➢ Constructor overloading is way of having more than one constructor which does different.
➢ Overloaded Constructors can be referred using this() keyword from other constructor.
Example 1.7:
class Overload{
Overload(){
System.out.println("Overloading constructor with no parameter");
}
Overload(int a){
System.out.println("Overloading constructor with parameter" +a);
}
Overload(int a, int b){
System.out.println("Overloading constructor with 2 parameter"
+ a + " " + b );
}
Overload(double a, double b){
System.out.println("Overloading constructor with different
type" + a + " " + b);
}
}

By, Suma M G, AP, MCA, RNSIT 4 | 27


JAVA Programming [20MCA22] Module-2

class ConstructorOver{
public static void main(String[] args){
Overload o1=new Overload();
Overload o2=new Overload(10);
Overload o3=new Overload(10,20);
Overload o4=new Overload(1.1,2.1);
}
}

Another Example for Method overloading and Constructor overloading: Lab Program
class Shape{
int length, breadth, height
Shape(){ //Default constructor
Length = breadth = height = 0;
}
Shape(int length, int breadt, int height) { // parameterized constructor
Length = breadth = height = side;
}
int volume() { // method with no parameters
return length * breadth * height;
}
int volume(int length, int breadth, int height) { // method with parameters
return length * breadth * height;
}
public static void main(String [] args){
System.out.println(“ --Demonstrating Constructor Overloading-- ”);
Shape square = new Shape(10);
Shape rectangle = new Shape();
System.out.println(“ --Demonstrating Method Overloading-- ”);
int volume1 = square.volume();
int volume2 = rectangle.volume(10,20, 30);
System.out.println(“ –Volume of Square = ” + volume1);
System.out.println(“ –Volume of Rectangle = ” + volume2);
}
}

1.7 Recursion:
A method can call itself. This process is called recursion. A method that calls itself is said to be recursive.
Why recursion:
✓ It requires the least amount of code to perform the necessary functions.
✓ Solves complicated problems in simple steps

By, Suma M G, AP, MCA, RNSIT 5 | 27


JAVA Programming [20MCA22] Module-2
When?
✓ The problem must be expressed in recursive manner
✓ There must be a condition which stops the recursion, otherwise there would be a stack overflow.
A recursive function has two parts:
✓ Base case: is stopping condition to prevent an infinite loop
✓ Recursive case: it must always get closer to base case from one invocation to another.
Example 1.8: Mathematical definition for
factorial of N number.

class Fact{
static int factorial(int n){
if (n == 0)
return 1;
else
return(n * factorial(n-1));//Recursively call
}
public static void main(String args[]){
int fact=1,number=4;
fact = factorial(number);
System.out.println("Factorial of "+ number+" is: "+fact);
}
}

1.8 Understanding Static:


Generally to accesses normal members of other class “an object is must”. But to Access Static member of
other class, object is not needed.
✓ Static members can be accessed before any objects of its class are created.
✓ Static members can be accessed using a dot operator with the class name.
Syntax:
className.staticVariable;
Example: main() method is declared as static
className.staticMethod(); because it must be called before any object.

The static can be:


1. variable (also known as class variable) 3. block
2. method (also known as class method)
Static Variables:
A data members of a class can be defined as static.
Syntax: className.staticVariable;

By, Suma M G, AP, MCA, RNSIT 6 | 27


JAVA Programming [20MCA22] Module-2
Characteristics:
• Instance variables declared as static are essentially, global variables
• It is visible only within the class, but its lifetime is the entire program.
• Only one copy of static data member will exists for the entire class and is shared by all the objects of
that class.
• No matter how many objects of a class are created.
• All static variables are initialized to zero when the first object of its class is created.
Example 1.9:

class Staticdata{
int x;
static int y;//Static Variable
void print(){
System.out.println("X= " + x + "\nY= " + y);
}
}
class StaticDemo{
public static void main(String[] args)
{
Staticdata std1=new Staticdata();
Staticdata std2=new Staticdata();
std1.print();
std2.print();
std1.x=5; //Accesing variable with class object
Staticdata.y=10; //Accessing static variable with class name
System.out.println("After modified");
std1.print();
std2.print();
}
}

Static Methods:
Method can also declared as static.
Syntax: className.staticMehtod();

Restriction:
• They can access only other static members of the class
• A static member does not have a this or super
• They cannot be declared as final
• A static member function can be called, even when a class is not instantiated.
• They cannot be a static and non-static version of the same method.

By, Suma M G, AP, MCA, RNSIT 7 | 27


JAVA Programming [20MCA22] Module-2
Example 1.10:

class StaticMethod{
int x;
static int y;
static void print(){ //Static Method
StaticMethod ob1=new StaticMethod();
//Instance variable can access with the object
System.out.println("X= " + ob1.x + "\nY= " + y);
}
}
class StaticDemoM{
public static void main(String[] args){
StaticMethod.print();//Invoking static method
}
}

Static Block:

Syntax: • Block can also declared as static.


static { • Is used to initialize the static data member.
-----
----- • It is executed before main method at the time of class loading.
}

Example 1.11:
class StaticBlock{
static double x;
static int y=10;
static{ //Static Block
System.out.println("Inside the static block");
x=Math.sqrt(2.0);
}
void print(){
System.out.println("X= " + x +"\nY= " + y);
}
}
class StaticDemoB{
public static void main(String[] args){
StaticBlock sb1=new StaticBlock();
sb1.print();
}
}

By, Suma M G, AP, MCA, RNSIT 8 | 27


JAVA Programming [20MCA22] Module-2
1.9 Introducing Nested and Inner Classes:
Nested class is a class defined within another class.
Syntax: class EnclosingClass { A nested class does not exist independently of its
enclosing class. Thus, the scope of a nested class is
-----
bounded by its outer class.
class NestedClass {
- - - - - There are 2 types of Nested Class:
} i. Static class
} ii. Non-Static class or Inner class
i. Static Nested Class
Syntax: class EnclosingClass {
-----
static class StaticNested{
- - - - -
}
}

Creating instance of static Nested class

EnclosingClass.StaticNested ob = new EnclosingClass.StaticNested();

ii. Non-Static Class:


Non-static nested classes are known as inner classes.
❖ It has access to all of the variables and methods of its outer class
❖ May refer to them directly in the same way that other non-static members of the outer class do.
Members of the inner class are known only within the scope of the inner class and may not be used by
the outer class.
Syntax: class OuterClass {
-----
class InnerClass {
- - - - -
}
}
Creating instance of inner class

OuterClass outOb = new OuterClass();


OuterClass.InnerClass inOb = outOb.new InnerClass();

By, Suma M G, AP, MCA, RNSIT 9 | 27


JAVA Programming [20MCA22] Module-2
Example 1.12
class Outer{
String str="Outer Class";
void show(){
Inner in=new Inner();
in.display();
}
class Inner{
String str1="Inner Class";
void display() {
System.out.println("Hello from display of Inner Class");
System.out.println("String-Outer: " + str);
System.out.println("String-Inner: " + str1);
}
}
}
class NestedDemo{
public static void main(String[] args){
Outer ou=new Outer();//Creating object to Outer Class
ou.show();
System.out.println("Calling through outer class object")
Outer.Inner ouin=ou.new Inner();//creating object to innerclass
ouin.display();
}
}

Another Example: Lab Program1(b)

1.10 Varargs: Variable-Length Arguments:


Varargs: stands for variable-length argument. A method that takes a variable number of arguments is called a
“variable- arity” method, or simply a varargs method.
Example: println()
Different ways to handle variable-length argument
• If the number of arguments was small and known, then use method overloading, one for each.
• If the number of arguments was larger or unknowable, then
➢ Use Array and add arguments into an array.
➢ Use three periods (...) to specify variable-length argument.

Syntax: <returnType> MethodName(int ... arrayName){

------
}

static void vaTest(int ... v){


Example:
------------------
}

By, Suma M G, AP, MCA, RNSIT 10 | 27


JAVA Programming [20MCA22] Module-2
Where,
▪ This syntax tells the compiler that vaTest( ) can be called with zero or more arguments.
▪ As a result, v is implicitly declared as an array of type int[ ].
▪ Thus, inside vaTest( ), v is accessed using the normal array syntax.

Example 1.13:

class VarArgs{
static void vaTest(int ...v){
System.out.println("Number of Arguments: " + v.length);
System.out.println("Contents");
for(int i=0;i<v.length;i++){
System.out.println("Arg " + (i+1) +": "+ v[i] + "\n");
}
}
public static void main(String[] args){
vaTest(10);
vaTest(1,2,3,4);
vaTest();
}
}

Additional Examples

Example 1: Logic of Multiplication of 2 natural numbers


❖ Multiplication of (a*b)
can be defined as Number
‘a’ added to itself b times

❖ Mathematical definition

Example 2: Logic of: generating


Fibonacci number for nth term

Mathematical definition

By, Suma M G, AP, MCA, RNSIT 11 | 27


JAVA Programming [20MCA22] Module-2
Example 3: Logic of generating Fibonacci number for nth term

By, Suma M G, AP, MCA, RNSIT 12 | 27


JAVA Programming [20MCA22] Module-2
Chapter-2

Inheritance

2.1. Inheritance Basics:


Inheritance is a mechanism in which one object acquires all the properties and behaviors of parent object. This
is done by using the ‘extends’ keyword.
Syntax: class Subclass-name extends Superclass-name{
//methods and fields
}
Where, extends keyword indicates that you are making a new class that derives from an existing class.
Example 2.1:

class Employee{
float salary = 40000;
}
class Programmer extends Employee {
int bonus = 10000;
public static void main(String args[]){
Programmer p = new Programmer();
System.out.println("Programmer salary is:" + p.salary);
System.out.println("Bonus of Programmer is " + p.bonus);
}
}

Why use Inheritance?


• To achieve Runtime Polymorphism using Method Overriding
• For Code Reusability.

Methods of Inheritance
• By extending a class:

• By implementing an interface:

Types of Inheritance:
There can be five types of inheritance:
1. Single or Simple Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
5. Hybrid Inheritance Supported by interface only

By, Suma M G, AP, MCA, RNSIT 13 | 27


JAVA Programming [20MCA22] Module-2
1. Single or Simple Inheritance:
There is just one base and derived class. class Base
{
Syntax: //methods and fields of Base class
class Base
}
extends class Derived extends Base
{
//methods and fields of Derived class
class Derived }

2. Multi-Level Inheritance:
There is just one base and one derived class at the same time at one level. At next level, the derived class becomes
base class for the next derived class.
class Base{
Syntax: class Base
//methods and fields of Base class
}
extends
class Derived1 extends Base{
class Derived1 //methods and fields of Derived class
}
extends class Derived2 extends Derived1{
//methods and fields of Derived class
class Derived2 }

3. Hierarchical Inheritance:
Multiple classes share the same base class i.e., number of classes inherit the properties of same base class. The
derived class may also become base class for other class.
class Base{
Syntax: class Base
//methods & fields of Base
}
class Derived1 extends Base{
extends
//methods & fields of Derived
class Derived1 class Derived2 }
class Derived2 extends Base{
extends //methods & fields of Derived
}
class Derived3 class Derived4

4. Multiple Inheritance:
A child can have more than one parent ie., a child can inherit properties from more than one base class. Doesn’t
support, but it support using interface.
Syntax:
class Base1 class Base2
extends Doesn’t support, but it support
using interface.

class Derived

By, Suma M G, AP, MCA, RNSIT 14 | 27


JAVA Programming [20MCA22] Module-2
Example:
class Base1{
//methods & fields of Base
}
class Base2{
//methods & fields of Base
}
class Derived extends Base1,Base2{
//methods & fields of Derived
}
5. Hybrid Inheritance:
It is the combination of hierarchical and multiple inheritance.
Syntax: class Base

extends Doesn’t support, but it support using


class Derived1 class Derived2 interface.
extends

class Derived3

2.2. Member Access and Inheritance:


• A subclass can access all the members of its superclass, it cannot access those members of the superclass
that have been declared as private.
• In a class hierarchy, private members remain private to their class. It is not accessible by any code outside
its class, including subclasses.
Example 2.2:
class Base{
class Access{
int i;
public static void main(String[] a)
private int j;
{
void setData(int x, int y){
Derived obj=new Derived();
i=x;
obj.setData(10, 20);
j=y;
obj.sum();
}
System.out.println("Total is:"
} + obj.total);
class Derived extends Base{ }
int total; }
void sum(){
//j has private access in Base
total= i+j;
}
}

By, Suma M G, AP, MCA, RNSIT 15 | 27


JAVA Programming [20MCA22] Module-2

• Java has a special access modifier known as protected which is meant to support Inheritance in Java.
• Any protected member including protected method and field are accessible for classes of same package and only
Sub class outside the package.

2.3. Constructors and Inheritance:


Constructor of base class with no argument gets automatically called in derived class constructor.
Example 2.3:

class Base{
Base(){
System.out.println("Base class constructors called");
}
}
class Derived extends Base{
Derived(){
System.out.println("Derived class constructors called");
}
}
public class Constructs{
public static void main(String[] args){
Derived obj=new Derived();
}
}
In the above example, when the object obj is created for the class Derived; the default constructor of a base class
Base is called automatically before the logic of the custom Derived constructor is executed.

When both the superclass and subclass define parameterized constructor, then the process is a bit more
complicated because both the superclass and subclass parameterized constructor must be executed. In this case,
“super” keyword can be used.

It has 2 general form:


i. Call a superclass constructor ii. Access members of the superclass in subclass

i.Using super to Call Superclass constructors:


A subclass can call a constructor defined by its super class.
Syntax: super(parameter_list);
Where,
▪ parameter_list specifies any parameter needed by the constructor in superclass().
▪ super() must be the first statement executed inside a subclass constructor.

By, Suma M G, AP, MCA, RNSIT 16 | 27


JAVA Programming [20MCA22] Module-2
Example 2.4:

class SuperC{
SuperC() {
System.out.println("Default constructor of super");
}
SuperC(String str){
System.out.println("Constructor of super displays :" + str);
}
}
class Sub extends SuperC{
Sub() {
super();
System.out.println("Constructor of Subclass");
}
Sub(String s1) {
super(s1);
System.out.println("parameter passed to Subclass");
}
}
class SuperDemo {
public static void main(String args[]){
Sub Ob = new Sub();
Sub Ob1=new Sub("RNSIT");
}
}

ii.Using “super” to Access Superclass Members:


• In Java ‘super’ keyword can be used to refer super class instance and method in a subclass.
• In other words super keyword is used by subclass whenever Syntax:
it need to refer to its immediate super class members. super.Mehtod();
• ‘super’ when used to access members need not be first line. super.variable;

Example 2.5: Accessing Shadowing instance variable and instance method.


• The ‘i’ instance variable and ‘show()’ instance method in class child shadows the instance variable and
instance method of parent class as both are having same name.
• If we display instance variable ‘i’ in sub class, it displays data of subclass. To access super class data
from shadowed variable, we use ‘super.i’.
• If we call overridden instance method ‘show()’ in sub class, it calls method of subclass itself. So to
overridden super class instance method from shadowed method, we use ‘super.show()’.

By, Suma M G, AP, MCA, RNSIT 17 | 27


JAVA Programming [20MCA22] Module-2

class Parent{
int i;
void show(){
System.out.println("i = " + i);
}
}
class Child extends Parent{
int i; //this i hides the i in A

Child(int a, int b){


super.i = a; //sets instance variable of super
i = b; //i in B
}
void show(){
super.show(); //calls method of super class
System.out.println("i in Super class= " + super.i);
System.out.println("i in subclass= " + i);
}}
class SuperDemo2{
public static void main(String args[]){
Child subob = new Child(10,20);
subob.show( );
}}

2.4. Creating a Multilevel Hierarchy:


There is just one base and one derived class at the same time at one level. At next level, the derived class becomes
base class for the next derived class.
Example 2.6:
Syntax: class Base class X{
public void methodX(){
extends
System.out.println("Class X method");
class Derived1 } }
class Y extends X{
extends public void methodY(){
System.out.println("class Y method");
class Derived2
} }
class Z extends Y{
public void methodZ(){
System.out.println("class Z method");
} }
class Demo{
public static void main(String args[]){
Z obj = new Z();
obj.methodX();
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}}

By, Suma M G, AP, MCA, RNSIT 18 | 27


JAVA Programming [20MCA22] Module-2
2.5. When are Constructors Executed:
Order of constructor execution in multilevel inheritance.
• When a class hierarchy is created, then the “constructors are called in order of derivation, from super
class to subclass”.
• If super is used to call constructor, since super() must be the first statement executed in a subclass
constructor, this order is the same whether or not super() is used.
• If super() is not used, then the default constructor of each super class will be executed.
• Subclass constructor is the last to execute.
Example 2.7:
class ClassA{ class DemoCH{
ClassA(){ public static void
System.out.println("Inside A constructor"); main(String args[]){
} ClassC obj = new ClassC();
} }
class ClassB extends ClassA{ }
ClassB(){
System.out.println("Inside B constructor");
}
}
class ClassC extends ClassB{
ClassC(){
System.out.println("Inside C constructor");
}
}

2.6. Superclass References and Subclass Objects:


❖ Super class reference variable
SuperClass parentOb = new SubClass();
can point to Sub Class Object.
❖ If you want to store object of Sub class, which is stored in super class reference variable as above, back
to Sub class reference then you need to use casting, as shown here:
SubClass childOb = (SubClass) parent;
Example 2.8:
class SuperA{ class SuRefDemo{
void showSuper(){ public static void main(String[] a)
System.out.println("Super class"); {
} SuperA SA = new SubB();
} SA.showSuper();
class SubB extends SuperA{ SA.showSub();//ERROR:
void showSub(){ }
System.out.println("Sub class"); }
}
}

By, Suma M G, AP, MCA, RNSIT 19 | 27


JAVA Programming [20MCA22] Module-2

• Accessing subclass overloaded methods using super reference


• Super class reference can’t access subclass methods even if they are overloaded.
• Super class reference can access subclass methods only if they are overridden which implements runtime
polymorphism

2.7. Method Overriding:


If subclass (child class) has the same method as declared in the parent class, it is known as method overriding.

Rules for overriding


• Instance methods can be overridden only if they are inherited by the subclass.
• private, static and final methods cannot be overridden in Java.
• Constructors cannot be overridden.
Example 2.9:

class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
public class TestDog{
public static void main(String args[]){
// Animal reference but Dog object
Animal bullDog = new Dog();
//Runs the method in Dog class
bullDog.move();
}
}

By, Suma M G, AP, MCA, RNSIT 20 | 27


JAVA Programming [20MCA22] Module-2
2.8. Overridden Methods support polymorphism (Dynamic Method Dispatch ):
Method overriding is a means of run time polymorphism; which method to call is based on object type, at runtime
time
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at run time,
rather than compile time.
Method to execute is based upon the type of the object being referred to at the time the call occurs.
Example 2.10:

class Animal{
public void move(){
System.out.println("Animals can move");
}
}
class Dog extends Animal{
public void move(){
System.out.println("Dogs can walk and run");
}
}
class Snake extends Animal{
public void move(){
System.out.println("Snake can't walk But run");
}
}
public class TestAnimalD{
public static void main(String args[]){
Animal animal = new Animal();
Snake cobra = new Snake();
Dog bullDog = new Dog();

animal.move(); //move in Animal class


animal = bullDog; //animal refers to Dog object
animal.move(); //move in Dog class
animal = cobra; //animal refers to Snake object
animal.move(); //move in Snake class
}
}

2.9. Why Overridden Methods:


• It allows a general class to specify methods that will be common to all derivatives, while allowing
subclasses to define the specific implementation of some or all of those methods.
• Overridden methods are another way that java implements the “one interface, multiple methods”.

By, Suma M G, AP, MCA, RNSIT 21 | 27


JAVA Programming [20MCA22] Module-2
Differences between Overloading and Overriding:

Method Overloading Method Overriding


Static polymorphism Runtime polymorphism
Method overloading is performed within class. Method overriding occurs in two classes.
Parameter must be different Parameter must be same.
Method overloading is the example of compile Method overriding is the example of run time
time polymorphism or static binding. polymorphism or dynamic binding.
Return type can be same or different Return type must be same

2.10. Using Abstract Classes:


A class that is declared with abstract keyword, is known as abstract class in java. It can have abstract and non-
abstract methods (method with body).
Syntax: public abstract class MyAbstractClass {
// code
}
✓ Abstraction is a process of hiding the implementation details and showing only functionality to the user.
✓ Purpose of an abstract class is to specify the default functionality of an object and let its sub-classes to
explicitly implement that functionality.
✓ An abstract class cannot be instantiated.
Important points of Abstract Classes:
• An abstract class is declared using the keyword abstract.
• It may or may not contain abstract methods
• An abstract class must be inherited by some other class.
• If the derived class does not provide the implementation of any abstract method present in an abstract
class, the derived class must be declared as abstract.
• Object of an abstract class cannot be created, but reference can be created.
• Through reference of abstract class, only methods of the abstract class implemented in the derived class
can be called.
• Abstract keyword cannot be applied to static methods or constructor.

Abstract Method:
An abstract method is a method that is declared without an implementation (without braces and followed by a
semicolon).
Syntax:
abstract Return-Type MyAbstractClass(arg-list);

An abstract method has no implementation. It just has a method signature.

By, Suma M G, AP, MCA, RNSIT 22 | 27


JAVA Programming [20MCA22] Module-2
Example 2.11:
abstract class Shape{ public class Point extends Shape {
public String color; static int x, y;
public Shape() { } public Point() {
public void setColor(String c){ x = 0;
color = c; y = 0;
} }
public String getColor() { public double area() {
return color; return 0;
} }
// abstract method public static void print() {
abstract public double area(); System.out.println("point: "
} + x + "," + y);
}
public static void main(String a[]){
Point p = new Point();
p.print();

p.setColor("Red");
System.out.println(p.getColor());
}
}

2.11. Using final:


The final keyword in java is used to restrict the user.
Final can be: ➢ variable ➢ method ➢ class

“final” variable:
If you make any variable as final, you cannot change the value of final variable (It will be constant).
Points
• a final variable that have no value it is called blank final variable or uninitialized final variable.
• Non-static final variable can be initialized either in the constructor or with the declaration.
• The static final variable can’t be assigned value in constructor; they must be assigned in the static block
only.
Example 2.12:
class FinalVar{ static{
final int i=90; //final variable x=100;
final int j;//blank final variable System.out.println("X= "+ x);
final static int x;//non-static final }
FinalVar(){ public static void main(String a[])
j=10; {
System.out.println("J= "+ j); FinalVar obj=new FinalVar();
} obj.run();
void run(){ }
//i=400; //can’t modified }
System.out.println("i= "+ i);
}

By, Suma M G, AP, MCA, RNSIT 23 | 27


JAVA Programming [20MCA22] Module-2
“final” method:
• A final method cannot be overridden by subclasses.
• This means even when a child class can call the final method of parent class without any issues but the
overriding will not be possible.
• Final methods are faster than non-final methods because they are not required to be resolved during
run-time and they are bonded on compile time.
• Final methods are bonded during compile time also called static binding.
Example 2.13:
class Stud{
final void show() {
System.out.println("Class - stud : method defined");
}
}
class Books extends Stud {
void show(){
System.out.println("Class - books : method defined");
}
}
class FinalMet{
public static void main(String args[]) {
Books B2 = new Books();
B2.show();
}
}

“final” Class:
• When a class is declared as final, it cannot be extended further.
• All methods in a final class are implicitly final.
Example 2.14:
final class Stud{
void show() {
System.out.println("Class - stud : method defined");
}
}
class Books extends Stud {
void show(){
System.out.println("Class - books : method defined");
}
}
class FinalCla{
public static void main(String args[]) {
Books B2 = new Books();
B2.show();
}
}

By, Suma M G, AP, MCA, RNSIT 24 | 27


JAVA Programming [20MCA22] Module-2
2.12. The Object Class:
• The Object class is the Super class of all the classes in java by default. This means that a reference
variable of type Object can refer to an object of any other class.
• Every class has Object as a
superclass.
• Every class you use or write
inherits the instance methods
of Object.

Example: Consider you have a super class called Circle and Subclass called PlaneCircle then it can be viewed
as shown below.

Your Class with


Object class

Object defines the following methods, which means that they are available in every object.

Method Purpose
Object clone() Creates a new object that is the same as the object being cloned.
boolean equals(Object object) Determines whether one object is equal to another.
void finalize() Called before an unused object is recycled
Class<?>getClass() Obtains the class of an object at run time
int hashCode() Returns the hash code associated with the invoking object
public final void notify() Resumes execution of a thread waiting on the invoking object
public final void notify All() Resumes execution of all threads waiting on the invoking objects
String toString() Returns a string that describes the object
void wait() Waits on another thread of execution
public final void wait (long milliseconds) throws InterruptedException
public final void wait (long milliseconds, int nanoseconds) throws InterruptedException

By, Suma M G, AP, MCA, RNSIT 25 | 27


JAVA Programming [20MCA22] Module-2
• getClass, notify, notifyall(), and wait are declared as final, can’t override it.
• equals() method compares two objects references
• toString() method returns the string.
Example 2.15: for getClass and toString() method
class Point{ public class GetClassDemo {
int x, y; public static void main(String[] a){
Point(int a, int b){ Point P1 = new Point(10, 20);
x=a; y=b; System.out.println(" "+P1.getClass());
}
System.out.println("Values : " + P1);
public String toString(){
return "x= "+ x +" ,y= "+ y ; }
} }
}

Example 2.16: for clone() method.


In java, if a class needs to support cloning it has to do following things:
➢ You must implement Cloneable interface.
➢ You must override clone() method from Object class.

class Point implements Cloneable{


int x,y;
Point(){
x=10; y=10;
}
protected Object clone() throws CloneNotSupportedException
{
return super.clone();
}
void showPoint(){
System.out.println("x = " + x + ", y = " + y);
}
}
public class CloneDemo{
public static void main(String[] args)
throws CloneNotSupportedException
{
Point pt = new Point();
Point ptclone = (Point) pt.clone();
ptclone.showPoint();
}
}

By, Suma M G, AP, MCA, RNSIT 26 | 27


JAVA Programming [20MCA22] Module-2

Questions:

1. A Closer Look at Methods and Classes


1. What is the difference between a method and constructor?
2. Explain constructor overloading and method overloading with an example program.
3. Explain about static variable, static method and static block with example.
4. What are instance variables and static variables? Explain with a suitable example program.
5. Briefly discuss about varargs.
6. Explain Inner class and its access protection with suitable examples.
7. Write a short note on:
i. Access Specifiers
ii. Object as parameters
2. Inheritance
1. Describe the various forms of inheritance.
2. How to call superclass constructors and superclass members using super? Explain with an example
program.
3. What is method overriding? How do you achieve runtime polymorphism in java?
4. What are the multiple usages of ‘final’ keyword in java?
5. What are the multiple usages of ‘super’ keyword in java?
6. Can final methods be overridden in subclass? Justify answer with an example.
7. Write a short notes on:
i. Object class
ii. clone()
iii. final class
iv. abstract class
v. abstract method
vi. Dynamic Method Dispatch
vii. super keyword
8. Difference between :
• Method Overloading and Method Overridden
• Abstract class and class

By, Suma M G, AP, MCA, RNSIT 27 | 27

You might also like