[go: up one dir, main page]

0% found this document useful (0 votes)
12 views45 pages

Unit 2 2022

Uploaded by

azhagansri2021
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)
12 views45 pages

Unit 2 2022

Uploaded by

azhagansri2021
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/ 45

CS3391 OBJECT ORIENTED PROGRAMMING

UNIT II INHERITANCE, PACKAGES AND INTERFACES 9


Overloading Methods – Objects as Parameters – Returning Objects –Static, Nested and Inner Classes.
Inheritance: Basics– Types of Inheritance -Super keyword -Method Overriding – Dynamic Method
Dispatch –Abstract Classes – final with Inheritance. Packages and Interfaces: Packages – Packages
and Member Access –Importing Packages – Interfaces.
1. Method Overloading in Java(Overloading Methods)
If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.

Different ways to overload the method


There are two ways to overload the method in java
1. By changing number of arguments
2. By changing the data type

1) Method Overloading: changing no. of arguments


In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.
class Adder
{
int add(int a,int b)
{
return a+b;
}
int add(int a,int b,int c)
{
return a+b+c;
}
}
class TestOverloading1
{
public static void main(String[] args)
{
Adder obj=new Adder();
System.out.println(obj.add(11,11));
System.out.println(obj.add(11,11,11));
}
}

Output:
Z:\javafiles>java TestOverloading
22
33
2) Method Overloading: changing data type of arguments
In this example, we have created two methods that differs in data type. The first add method receives
two integer arguments and second add method receives two double arguments.

CS3391 UNIT2( OOP) Page 1


class Adder
{
int add(int a, int b)
{
return a+b;
}
double add(double a, double b)
{
return a+b;
}
}
class TestOverloading2
{
public static void main(String[] args)
{
Adder obj=new Adder();
System.out.println(obj.add(11,11));
System.out.println(obj.add(12.3,12.6));
}
}
Output:

Z:\javafiles>java TestOverloading2
22
24.9

3. Method Overloading: changing order of arguments


In this example, we have created two methods that differ in order. The first add method receives first
argument as integer second as string and second add method receives first argument as string second
as integer.

class Showclass
{
void show(int rollno, String name)
{
System.out.println("rollno"+ rollno);
System.out.println("name"+name);
}

void show(String name, int rollno)


{
System.out.println("rollno"+rollno);
System.out.println("name"+name);
}
}
class TestOverloading3
{
public static void main(String[] args)

CS3391 UNIT2( OOP) Page 2


{
Showclass obj=new Showclass();
obj.show(11,"John");
obj.show("MichelJohn",11);
}
}
Output:
Z:\javafiles>java TestOverloading3
rollno11
nameJohn
rollno11
nameMichelJohn
Advantage of method overloading
Method overloading increases the readability of the program.

2.OBJECTS AS PARAMETERS – RETURNING OBJECTS


 Although Java is strictly passed by value, the precise effect differs between whether a primitive type or
a reference type is passed.
 When we pass a primitive type to a method, it is passed by value.
 But when we pass an object to a method, the situation changes dramatically, because objects are
passed by what is effectively call-by-reference.

 While creating a variable of a class type, we only create a reference to an object. Thus, when
we 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 act as if they are passed to methods by use of call-by-
reference.
 Changes to the object inside the method do reflect the object used as an argument.

call-by-reference.

Illustration: Let us suppose three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:
ObjectPassDemo ob1 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob2 = new ObjectPassDemo(100, 22);
ObjectPassDemo ob3 = new ObjectPassDemo(-1, -1);

From the method side, a reference of type ObjectPassDemo with a name o is declared and it’s
initially assigned to null.

CS3391 UNIT2( OOP) Page 3


boolean equalTo(ObjectPassDemo o);

As we call the method equalTo, the reference ‘o’ will be assigned to the object which is passed as an
argument, i.e. ‘o’ will refer to ‘ob2’ as the following statement execute.

System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));

Now as we can see, equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob2’. Since values of
‘a’ and ‘b’ are same for both the references, so if(condition) is true, so boolean true will be return.
if(o.a == a && o.b == b)

Again ‘o’ will reassign to ‘ob3’ as the following statement execute.


System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));

 Now as we can see, the equalTo method is called on ‘ob1’ , and ‘o’ is referring to ‘ob3’. Since
values of ‘a’ and ‘b’ are not the same for both the references, so if(condition) is false, so else
block will execute, and false will be returned.

CS3391 UNIT2( OOP) Page 4


Example 1:
 Enter length and breadth of rectangle as input.
 After that we create object of that class and pass the reference variable to method.
 Now we calculate area for object and return object to main method. Hence we get areas as
output.
Source code -To Implement the Concept of Passing the Object and Return Object
import java.util.Scanner;
public class ObjectPassReturn
{
int length, breadth, area;
ObjectPassReturn area1(ObjectPassReturn object1)// PASSING OBJECT AS ARGUMENT
{
length=object1.length ;
breadth=object1.breadth ;
area = object1.length * object1.breadth;
return (this); // RETURNING OBJECT

}
public static void main(String[] args)
{
ObjectPassReturn obj = new ObjectPassReturn();
Scanner s = new Scanner(System.in);
System.out.print("Enter length:");
obj.length = s.nextInt();
System.out.print("Enter breadth:");
obj.breadth = s.nextInt();
ObjectPassReturn a = obj.area1(obj);
System.out.println("Area:"+a.area);
}
}
OUTPUT:

Enter length:12
Enter breadth:10
Area:120
EXAMPLE2:
class Test
{
int a;

Test(int i)
{
a = i;
}
Test incrByTen(Test tobj) // PASSING OBJECT AS ARGUMENT
{
Test temp=tobj;
temp.a= tobj.a+10;
return temp; // RETURNING OBJECT

CS3391 UNIT2( OOP) Page 5


}
}

public class JavaProgram


{
public static void main(String args[])
{

Test obj1 = new Test(2);


Test obj2;

obj2 = obj1.incrByTen(obj1);

System.out.println("obj1.a : " + obj2.a);


obj2 = obj1.incrByTen(obj1);
System.out.println("obj2.a : " + obj2.a);

}
}

OUTPUT:
obj1.a : 12
obj2.a : 22

3.STATIC NESTED AND INNER CLASSSES

Nested Class
Java allows us to define a class within a class that is known as a nested class. It may be static or non-
static.
1. Java supports Static Instance Variables, Static Methods, Static Block, and Static Classes.
2. The class in which the nested class is defined is known as the Outer Class.
3. Unlike top-level classes, Inner classes can be Static.
4. Non-static nested classes are also known as Inner classes.

 An instance of an inner class cannot be created without an instance of the outer class.
 Therefore, an inner class instance can access all of the members of its outer class, without
using a reference to the outer class instance

Inner class
 The classes that are non-static and nested are called inner classes.
 Note that we cannot create an instance of the inner class without creating an instance of the
outer class.
 Without using the reference to the outer class instance, an instance of the inner class can
access the members of its outer class. It makes the program simple and concise.
Outer Class
The class in which nested class is defined is called outer class

The major difference between static and non-static class is that:


CS3391 UNIT2( OOP) Page 6
 An instance of the static nested class can be created without creating an instance of its outer class.
 The static and non-static members of an outer class can be accessed by an inner class.
 The static members of the outer class can be accessed only by the static class.

1.STATIC CLASS

We can declare a class static by using the static keyword. A class can be declared static only if it is a
nested class. It does not require any reference of the outer class. The property of the static class is
that it does not allows us to access the non-static members of the outer class.

To understand the concept of static class first we need to understand the concept of inner, outer, and
nested class.

Example:

public class JavaStaticClassExample

{
private static String s= "SECOND YEAR";
//Static and nested class
static class StaticNestedClass
{
//non-static method of the nested class
public void show()
{
//prints the string defined in base class
System.out.println(s);
}
}
public static void main(String args[])

CS3391 UNIT2( OOP) Page 7


{
JavaStaticClassExample.StaticNestedClass obj = new JavaStaticClassExample.StaticNestedClass();
//invoking the method of the nested class
obj.show();
}
}
OUTPUT:
SECOND YEAR

Note:

1. All static classes are nested classes but vice-versa is not true.
2. It can access only static members of the outer class.
3. Non-static variable and instance methods cannot be accessed within the static class.
4. If you try to access a non-static reference from a static field, it throws an error: Cannot make
a static reference to the non-static field.
5. We can create static blocks, variables, and methods inside a static class.
6. A class may have multiple static classes.
7. We cannot access the static class if it is inside the static block.
8. There may be any number of static classes within a static class.

2.INNER CLASSSES
 Java inner class or nested class is a class which is declared inside the class or interface.
 We use inner classes to logically group classes and interfaces in one place so that it can be more
readable and maintainable.
 Additionally, it can access all the members of outer class including private data members and
methods.

Syntax

class Outer_Demo
{
class Inner_Demo
{
}
}
 Inner classes are a security mechanism in Java. We know a class cannot be associated with the
access modifier private, but if we have the class as a member of other class, then the inner
class can be made private. And this is also used to access the private members of a class.
 Inner class means one class which is a member of another class.
 To instantiate an inner class, you must first instantiate the outer class. Then, create the inner
object within the outer object with this syntax:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

CS3391 UNIT2( OOP) Page 8


Example:
class Outer
{
// Simple nested inner class
class Inner
{
public void show()
{
System.out.println("In a nested class method");
}
}
}
class Main
{
public static void main(String[] args)
{
Outer o=new Outer();
Outer.Inner in = o.new Inner();
in.show();
}
}
Output:
In a nested class method

Inner classes are of two types


1. Method-local Inner Class
2. Anonymous Inner Class

2.1Method-local Inner Class

Inner class can be declared within a method of an outer class. In the following example, Inner is an
inner class in outerMethod().
class Outer
{
void outerMethod()
{
System.out.println("inside outerMethod");

class Inner
{
void innerMethod()
{
System.out.println("inside innerMethod");
}
CS3391 UNIT2( OOP) Page 9
}
Inner y = new Inner();
y.innerMethod();
}
}
class MethodDemo
{
public static void main(String[] args)
{
Outer x = new Outer();
x.outerMethod();
}
}

Output
Inside outerMethod
Inside innerMethod

2.2.Anonymous inner classes


Anonymous inner classes are declared without any name at all.
They are created in two ways.
1. Anonymous Inner class that extends a class
2. Anonymous Inner class that implements a interface
1.Anonymous Inner class that extends a class

class Demo
{
void show()
{
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo
{

// An anonymous class with Demo as base class


static Demo d = new Demo()
{
void show()
{
super.show();
System.out.println("i am in Flavor1Demo class");
}
};
public static void main(String[] args){
d.show();
}
}

CS3391 UNIT2( OOP) Page 10


Output
i am in show method of super class
i am in Flavor1Demo class

2.Anonymous Inner class that implements an interface

interface Hello
{
void show();
}

class Flavor2Demo
{

// An anonymous class that implements Hello interface


static Hello h = new Hello()
{
public void show()
{
System.out.println("i am in anonymous class");
}
};

public static void main(String[] args) {


h.show();
}
}

Output
i am in anonymous class

Advantage of java inner classes


There are basically three advantages of inner classes in java.
They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members
(data members and methods) of outer class including private.
2) Nested classes are used to develop more readable and maintainable code because it
logically group classes and interfaces in one place only.
3) Code Optimization: It requires less code to write.

4.Inheritance –Basics
Super classes- sub classes
Inheritance is the process by which one object acquires the properties of another object.
1. The class which inherits the properties of other is known as subclass (derived class, child class)
and the class whose properties are inherited is known as superclass (base class, parent class).

CS3391 UNIT2( OOP) Page 11


i. 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.
2. Inheritance represents the IS-A relationship, also known as parent-child relationship.

Inheritance Basics
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.
Syntax
class Super
{
…..
…..
}
Class Sub extends Super
{
….
….
}

Example
The following program creates a super class called A and a subclass called B. Notice how the
keyword extends is used to create a subclass of A.
// Create a superclass.
class A
{
int i, j;
void showij()
{
System.out.println("i and j: " + i + " " + j);
}
}
// Create a subclass by extending class A.

class B extends A
{
int k;
void showk()
{
System.out.println("k: " + k);
}
}
Example Program:
class Teacher
{
String designation = "Teacher";
String collegeName = "AAMEC";
void does()
{
System.out.println("Teaching");
CS3391 UNIT2( OOP) Page 12
}
}

public class PhysicsTeacher extends Teacher


{
String mainSubject = "Physics";
public static void main(String args[])
{
PhysicsTeacher obj = new PhysicsTeacher();
System.out.println(obj.collegeName);
System.out.println(obj.designation);
System.out.println(obj.mainSubject);
obj.does();
}
}
Output:
AAMEC
Teacher
Physics
Teaching

 Based on the above example we can say that PhysicsTeacher IS-A Teacher.
 This means that a child class has IS-A relationship with the parent class. This is inheritance is
known as IS-A relationship between child and parent class

Member Access and Inheritance

Although a subclass includes all of the members of its super class, it cannot access those members of
the super class that have been declared as private.
Example
// Create a superclass.
class A
{
int i; // public by default
private int j; // private to A
void setij(int x, int y)
{
i = x;
j = y;
}
}
// A's j is not accessible here.
class B extends A
{
int total;
void sum()
{
total = i + j; // ERROR, j is not accessible here
}
CS3391 UNIT2( OOP) Page 13
}
Example Program:
class Calculation
{
int z;
public void addition(int x, int y)
{
z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y)


{
z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}

public class My_Calculation extends Calculation


{
public void multiplication(int x, int y)
{
z = x * y;
System.out.println("The product of the given numbers:"+z);
}

public static void main(String args[])


{
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}

5.Types of Inheritance
1.Single Inheritance:
When a single class is derived from on single base class is known as single inheritance.

CS3391 UNIT2( OOP) Page 14


Single Inheritance example program in Java
Class A
{
public void methodA()
{
System.out.println("Base class method");
}
}

Class B extends A
{
public void methodB()
{
System.out.println("Child class method");
}
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling local method
}
}

2.Multiple Inheritance: When one single class is derived from more than one base class is known as
multiple inheritance.

 Most of the new OO languages like Small Talk, Java, C# do not support Multiple
inheritance.
 Multiple Inheritance is supported in C++.
Multilevel Inheritance: When a class is derived from a class which is derived from some other class
for which this class is a derived class is known as multilevel Inheritance.

CS3391 UNIT2( OOP) Page 15


Multilevel Inheritance example program in Java
Class X
{
public void methodX()
{
System.out.println("Class X method");
}
}
Class Y extends X
{
public void methodY()
{
System.out.println("class Y method");
}
}
Class Z extends Y
{
public void methodZ()
{
System.out.println("class Z method");
}
public static void main(String args[])
{
Z obj = new Z();
obj.methodX(); //calling grandparent class method
obj.methodY(); //calling parent class method
obj.methodZ(); //calling local method
}
}

Hierarchical Inheritance: When more than one class is derived from an existing class is known as
Hierarchical inheritance.

CS3391 UNIT2( OOP) Page 16


Hierarchical Inheritance example program in Java

class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class JavaExample
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
//All classes can access the method of class A
obj1.methodA();
obj2.methodA();
obj3.methodA();
}
}

Hybrid Inheritance: An inheritance which is mix of more than one type of inheritance is known as
Hybrid Inheritance. A hybrid inheritance is a combination of more than one types of inheritance.

CS3391 UNIT2( OOP) Page 17


Hybrid Inheritance example program in Java
For example when class A and B extends class C & another class D extends class A then this is a
hybrid inheritance, because it is a combination of single and hierarchical inheritance.
Let me show you this diagrammatically:

class C
{
public void disp()
{
System.out.println("C");
}
}

class A extends C
{
public void disp()
{
System.out.println("A");
}
}

class B extends C
{
public void disp()
{
System.out.println("B");
}

CS3391 UNIT2( OOP) Page 18


}

class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){

D obj = new D();


obj.disp();
}
}

Inheriting in different access Modes (or )Access Control and Inheritance:


A class can be inherited in three different modes i.e. Public, Private and Protected mode.
Note:
 Only Public and Protected members can be inherited to derived class.
 In any case private members can’t be inherited

Private inheritance When a class is derived in private mode then all the public and protected
members will be private for the derived class.
Public inheritance When a class is derived in public mode then the protected members will be
protected and public members will be public for the derived class.
Protected inheritance When a class is derived in protected mode then all the protected members as
well as the public members will be protected for the derived class.

The relation between mode of inheritance and its parent class scope can be classified as follows

6. Super keyword

The super keyword in Java is a reference variable which is used to refer immediate parent class
object.

Whenever you create the instance of subclass, an instance of parent class is created implicitly which
is referred by super reference variable.

Usage of java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.

CS3391 UNIT2( OOP) Page 19


1. Using super to refer immediate parent class instance variable.

We can use super keyword to access the data member or field of parent class. It is used if parent
class and child class have same fields.

class Animal
{
String color="white";
}
class Dog extends Animal
{
String color="black";
void printColor()
{
System.out.println(color); //prints color of Dog class
System.out.println(super.color); //prints color of Animal class
}
}
class TestSuper1
{
public static void main(String args[])
{
Dog d=new Dog();
d.printColor();
}
}

Output:
black
white
2. Using super to invoke immediate parent class method
The super keyword can also be used to invoke parent class method.
It should be used if subclass contains the same method as parent class.

In other words, it is used if method is overridden.

class Animal
{
void eat(){System.out.println("eating...");
}
}
class Dog extends Animal
{
void eat(){System.out.println("eating bread...");
}
void bark(){System.out.println("barking...");
}
CS3391 UNIT2( OOP) Page 20
void work()
{
super.eat();
bark();
}
}
class TestSuper2
{
public static void main(String args[])
{
Dog d=new Dog();
d.work();
}
}

Output:

eating...
barking...

3.Using super to Call Superclass Constructors(Constructors in sub classes)


A subclass can call a constructor defined by it’s super class by use of the following form of super:
super (arg-list);
Here, arg-list specifies any arguments needed by the constructor in the super class.
Example
class cubic extends rect
{
int h;
cubic(int n1,int n2,int n3)
{
super(n1,n2);
h=n3;
}
}
Here, cubic ( ) calls super( ) with the arguments n1, n2, and n3. This causes the rect( ) constructor to
be called, which initializes l, b, and h using these values.
Example
A complete implementation
class rect
{
int l,b;
rect(int n1,int n2)
{
l=n1;
b=n2;
}
}
class cubic extends rect
{
int h;
CS3391 UNIT2( OOP) Page 21
cubic(int n1,int n2,int n3)
{
super(n1,n2);
h=n3;
}
}
class cubicdemo
{
public static void main(String args[])
{

cubic obj=new cubic(20,40,5);


System.out.println("Area of rectangle="+(obj.l*obj.b));
System.out.println("Area of cubic rectangle="+(obj.l*obj.b*obj.h));
}
}
Output:
Z:\javafiles>java cubicdemo
Area of rectangle=800
Area of cubic rectangle=4000
Inheritance: Code reuse using subclass and super class relationship
Advantage of Inheritance :

The biggest advantage of Inheritance is that the code that is already present in base class need not
be rewritten in the child class.
1.Reusability The biggest advantage of Inheritance is that the code that is already present in base
class need not be rewritten in the child class.
2.Code more flexible change
Inheritance can also make application code more flexible to change because classes that inherit from
a common superclass can be used interchangeably. If the return type of a method is superclass.
3.Better organization of code
Moving of common code to superclass results in better organization of code.
4.Minimize the amount of duplicate code in an application

Disadvantage:
The inheritance relationship is a, tightly coupled relationship , there will be tight bonding between
parent and child. If we change code of parent class it will get affects to the all the child classes which
is inheriting the parent code.

7.Dynamic Method Dispatch or Runtime Polymorphism


Method overriding is one of the ways in which Java supports Runtime Polymorphism.
Method Overriding
When a method in a sub class has same name, same number of arguments and same type signature as
a method in its super class, then the method is known as overridden method.
 Method overriding is also referred to as runtime polymorphism.

Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
run time, rather than compile time.

CS3391 UNIT2( OOP) Page 22


1. When an overridden method is called through a superclass reference, Java determines which
version(superclass/subclasses) of that method is to be executed based upon the type of the
object being referred to at the time the call occurs. Thus, this determination is made at run
time.
2. At run-time, it depends on the type of the object being referred to (not the type of the
reference variable) that determines which version of an overridden method will be executed
3. A superclass reference variable can refer to a subclass object. This is also known as upcasting.
Java uses this fact to resolve calls to overridden methods at run time.

if a superclass contains a method that is overridden by a subclass, then when different types of

objects are referred to through a superclass reference variable, different versions of the
method are executed.:
Example 1: Illustrates dynamic method dispatch

// A Java program to illustrate Dynamic Method Dispatch using hierarchical inheritance


class A
{
void m1()
{
System.out.println("Inside A's m1 method");
}
}

class B extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside B's m1 method");
}
}

class C extends A
{
// overriding m1()
void m1()
{
System.out.println("Inside C's m1 method");
}
}

// Driver class
class Dispatch
{
public static void main(String args[])
{
A ref;

// ref refers to an A object

CS3391 UNIT2( OOP) Page 23


ref = new A();;

// calling A's version of m1()


ref.m1();

// now ref refers to a B object


ref = new B();

// calling B's version of m1()


ref.m1();

// now ref refers to a C object


ref = new C();

// calling C's version of m1()


ref.m1();
}
}

Output:

Inside A's m1 method


Inside B's m1 method
Inside C's m1 method

Explanation:
Now we are assigning a reference to each type of object (either A’s or B’s or C’s) to ref, one-by-one,
and uses that reference to invoke m1( ). As the output shows, the version of m1( ) executed is
determined by the type of object being referred to at the time of the call.
ref = a; // r refers to an A object
ref.m1(); // calling A's version of m1()

ref = b; // now r refers to a B object


ref.m1(); // calling B's version of m1()

CS3391 UNIT2( OOP) Page 24


ref = c; // now r refers to a C object
ref.m1(); // calling C's version of m1()

Example 2:Dynamic Method Dispatch


class Animal
{
public void eat()
{
System.out.println("Generic Animal eating");
}
}

class Dog extends Animal


{
public void eat() //eat() method overriden by Dog class.
{
System.out.println("Dog eat meat");
}
}

class overridingdemo
{
public static void main(String[] args)

CS3391 UNIT2( OOP) Page 25


{

Animal obj =new Animal();


obj.eat();
Dog obj2=new Dog();
obj2.eat();
}
}
Output:
Z:\javafiles>java overridingdemo
Generic Animal eating
Dog eat meat

Difference between Overloading and Overriding


Method Overloading Method Overriding
Parameter must be different and name must be Both name and parameter must be same.
same.
Compile time polymorphism. Runtime polymorphism.
Increase readability of code. Increase reusability of code.
Constructors can be overloaded Constructors cannot be overridden

Method overloading is performed within class. Method overriding occurs in two classes (one in
base class and another in derived class)

Method overloading is the example of compile Method overriding is the example of run time
time polymorphism. polymorphism.
Access specifier can be changed. Access specifier cannot be more restrictive than
original method(can be less restrictive).

Advantages of Dynamic Method Dispatch

1. Dynamic method dispatch allow Java to support overriding of methods which is central for
run-time polymorphism.
2. It allows a class to specify methods that will be common to all of its derivatives, while
allowing subclasses to define the specific implementation of some or all of those methods.
3. It also allow subclasses to add its specific methods subclasses to define the specific
implementation of some.

Static vs Dynamic binding

 Static binding is done during compile-time while dynamic binding is done during run-time.
 private, final and static methods and variables uses static binding and bonded by compiler
while overridden methods are bonded during runtime based upon type of runtime object

CS3391 UNIT2( OOP) Page 26


9.Abstract Classes
When we define a class to be “final”, it cannot be extended. In certain situation, we want to properties
of classes to be always extended and used. Such classes are called Abstract Classes.
1. An Abstract class is a conceptual class.
2. An Abstract class cannot be instantiated – objects cannot be created.
3. Abstract classes provides a common root for a group of classes, nicely tied together in a
package
Abstract Class Syntax
abstract class ClassName
{ ...

abstract Type MethodName1();
……
Type Method2()
{
// method body
}
}

 When a class contains one or more abstract methods, it should be declared as abstract class.
 The abstract methods of an abstract class must be defined in its subclass.
 We cannot declare abstract constructors or abstract static methods.
Example
 Consider the following class hierarchy consisting of a Shape class which is inherited by three
classes Rectangle, Circle, and Triangle.
 The Shape class is created to save on common attributes and methods shared by the three
classes Rectangle, Circle, and Triangle.
 Area() is one such method shared by all three child classes and present in Shape class.

Program:
import java.io.*;
abstract class shape
{
String shapetype;
abstract double area();
void display(String st)
{
System.out.println("Shapetype="+st);
}
}
class circle extends shape
{
int r=50;

CS3391 UNIT2( OOP) Page 27


double area() //implementing abstract method area()
{
return 3.14*r*r;
}
}
class rectangle extends shape
{
int l=50,b=40;
double area() //implementing abstract method area()
{
return l*b;
}
}

class triangle extends shape


{
int b=50,h=40;
double area() //implementing abstract method area()
{
return 0.5*b*h;
}
}

class shapedemo
{
public static void main(String args[])
{
circle c=new circle();
c.display("circle");
System.out.println("The Area is"+c.area());
rectangle r =new rectangle();
r.display("rectangle");
System.out.println("The Area is"+r.area());
triangle t=new triangle();
t.display("triangle");
System.out.println("The Area is"+t.area());
}
}
Output:
Z:\javafiles>java shapedemo
Shapetype=circle
The Area is7850.0
Shapetype=rectangle
The Area is2000.0
Shapetype=triangle
The Area is1000.0

CS3391 UNIT2( OOP) Page 28


Abstract Classes Properties
 An abstract class may also have concrete (complete) methods.
 A class with one or more abstract methods is automatically abstract and it cannot be
instantiated.
 A class declared abstract, even with no abstract methods can not be instantiated.
 A subclass of an abstract class can be instantiated if it overrides all abstract methods by
implementation them.
 A subclass that does not implement all of the superclass abstract methods is itself
abstract; and it cannot be instantiated.

Abstract Method

An abstract method is a method that is declared without an implementation (without braces, and
followed by a semicolon), like this:

public abstract int sumOfTwo (int n1, int n2);

if a class includes abstract methods, then the class itself must be declared abstract, as in:

abstract class Sum


{
public abstract int sumOfTwo(int n1, int n2);
//Regular or concrete method
public void disp()
{
System.out.println("Method of class Sum");
}
}

Rules of Abstract Method

1. Abstract methods don’t have body, they just have method signature as shown above.
2. If a class has an abstract method it should be declared abstract, the vice versa is not true, which
means an abstract class doesn’t need to have an abstract method compulsory.
3. If a regular class extends an abstract class, then the class must have to implement all the abstract
methods of abstract parent class or it has to be declared abstract as well.

Example 1: Abstract method in an abstract class


abstract class Sum
{
public abstract int sumOfTwo(int n1, int n2);
public abstract int sumOfThree(int n1, int n2, int n3);

public void disp() //Regular method

{
System.out.println("Method of class Sum");
}

CS3391 UNIT2( OOP) Page 29


}
class Demo extends Sum //Regular class extends abstract class
{
/* If you don't provide the implementation of these two methods,
the program will throw compilation error. */
public int sumOfTwo(int num1, int num2)
{
return num1+num2;
}
public int sumOfThree(int num1, int num2, int num3){
return num1+num2+num3;
}

public static void main(String args[])


{
Sum obj = new Demo();
System.out.println(obj.sumOfTwo(3, 7));
System.out.println(obj.sumOfThree(4, 3, 19));
obj.disp();
}
}
Output:
10
26
Method of class Sum
Example 2: abstract method in interface
All the methods of an interface are public abstract by default. We cannot have concrete (regular
methods with body) methods in an interface.
interface Multiply
{
//abstract methods
public abstract int multiplyTwo(int n1, int n2);
int multiplyThree(int n1, int n2, int n3);
/* We need not to mention public and abstract in interface as all the methods in interface are
* public and abstract by default so the compiler will treat this as public abstract multiplyThree(int n1, int n2, int n3); */
}

10. Final with Inheritance


Final methods and classes
The final keyword in java is used to restrict the user. The java final keyword can be used in many
context.
Final can be:
1. variable
2. method
3. class

CS3391 UNIT2( OOP) Page 30


1) Java final variable
If you make any variable as final, you cannot change the value of final variable(It will be constant).
 The only difference between a normal variable and a final variable is that we can re-assign value to a
normal variable but we cannot change the value of a final variable once assigned.
 It can't be changed because final variable once assigned a value can never be changed.
Example:
class Bike
{
final int speedlimit=90;//final variable
void run()
{
speedlimit=400;
}
public static void main(String args[])
{
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:Compile Time Error

2.Java final method


We use the final keyword in a method declaration to indicate that the method cannot be overridden by
subclasses.
If you make any method as final, you cannot override it.
Example of final method
class Bike
{
final void run()
{
System.out.println("running");}
}

class Honda extends Bike


{
void run()
{
System.out.println("running safely with 100kmph");
CS3391 UNIT2( OOP) Page 31
}
public static void main(String args[])
{
Honda honda= new Honda();
honda.run();
}
}
Output:Compile Time Error

3) Java final class


If you make any class as final, you cannot extend it.
final class Bike
{
}
class Honda1 extends Bike
{
void run()
{
System.out.println("running safely with 100kmph");
}
public static void main(String args[])
{
Honda1 honda= new Honda1();
honda.run();
}
}
Output:Compile Time Error

1. final method is inherited but you cannot override it.


2. Blank final variable :A final variable that is not initialized at the time of declaration is
known as blank final variable.
class Student
{
int id;
String name;
final String PAN_CARD_NUMBER;
...
}
3. It can be initialized only in constructor.

class Student
CS3391 UNIT2( OOP) Page 32
{
int id;
String name;
final String PAN_CARD_NUMBER;

Student()
{
PAN_CARD_NUMBER=”AZkP1234567”;
System.out.println(PAN_CARD_NUMBER);
}
public static void main(String args[])
{
Student s=new Student ();
}
}

4. Since private methods are inaccessible, they are implicitly final in Java. So
adding final specifier to a private method doesn’t add any value.
Points to Remember:
1) A constructor cannot be declared as final.
2) Local final variable must be initializing during declaration.
3) All variables declared in an interface are by default final.
4) We cannot change the value of a final variable.
5) A final method cannot be overridden.
6) A final class not be inherited.
7) If method parameters are declared final then the value of these parameters cannot be changed.
8) It is a good practice to name final variable in all CAPS.
9) final, finally and finalize are three different terms. finally is used in exception handling and finalize
is a method that is called by JVM during garbage collection.

ABSTRACT CLASS FINAL CLASS


1. Abstract class methods functionality 1. Final class methods functionality cannot be
can be altered in subclass. altered in subclass. (used as it is by other
classes)
2. Cannot be instantiated 2. Can be instantiated
3. Can be inherited 3. Cannot be inherited
4. Should be sub classed to override the 4. Can never be sub classed as final does not
functionality of abstract methods permit
5. Abstract methods should be 5. final class methods cannot be inherited, so it

CS3391 UNIT2( OOP) Page 33


overridden cannot be overridden
6. Can contain abstract methods 6. Cannot contain abstract methods
7. It is an incomplete class 7. It is a complete class

12. Packages and Member Access


Packages In Java
A java package is a group of similar types of classes, interfaces and sub-packages.

Package in java can be categorized in two forms,


1)User defined package: The package we create is called user-defined package.
2) Built-in package: The already defined package like java.io.*, java.lang.* etc are known as built-in
package

1.Built-in Packages

These packages consist of a large number of classes which are a part of Java API.Some of the
commonly used built-in packages are:

1) java.lang: Contains language support classes(e.g classed which defines primitive data types, math
operations). This package is automatically imported.

2) java.io: Contains classed for supporting input / output operations.

3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and
support ; for Date / Time operations.

4) java.applet: Contains classes for creating Applets.

5) java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).

6) java.net: Contain classes for supporting networking operations.

Example:
import java.util.Scanner
Here:
→ java is a top level package
→ util is a sub package
→ and Scanner is a class which is present in the sub package util.

CS3391 UNIT2( OOP) Page 34


2.User-defined packages

These are the packages that are defined by the user.

Creating a Package

The package keyword is used to create a package in java.

//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}

How to compile java package

If you are not using any IDE, you need to follow the syntax given below:

javac -d directory javafilename

For example

javac -d . Simple.java

CS3391 UNIT2( OOP) Page 35


The -d switch specifies the destination where to put the generated class file. You can use any
directory name like /home (in case of Linux), d:/abc (in case of windows) etc. If you want to keep the
package within the same directory, you can use . (dot).

How to run java package program

You need to use fully qualified name e.g. mypack.Simple etc to run the class.

To Compile: javac -d . Simple.java

To Run: java mypack.Simple

Output:Welcome to package

IMPORTING AND MEMBER ACCESS IN PACKAGES

How to import Java Package?

To import java package into a class, we need to use java import keyword which is used to access
package and its classes into the java program.

Use import to access built-in and user-defined packages into your java source file so that your class
can refer to a class that is in another package by directly using its name.

There are 3 different ways to refer to any class that is present in a different package:

1. import package with all classes


2. import package with specified class
3. without import the package

Member Access in Package

How to access package from another package?

There are three ways to access the package from outside the package.

1. Using packagename.* ( import package.*;)


2. Using packagename.classname (import package.classname;)
3. Using fully qualified name

1) Using packagename.*

If you use package.* then all the classes and interfaces of this package will be accessible but not
subpackages.

The import keyword is used to make the classes and interface of another package accessible to the
current package.
CS3391 UNIT2( OOP) Page 36
Example of package that import the packagename.*

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;

class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
Output:Hello

2) Using packagename.classname

If you import package.classname then only declared class of this package will be accessible.

Example of package by import package.classname

//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.A;

class B{
public static void main(String args[])
{
A obj = new A();
obj.msg();
}
}
CS3391 UNIT2( OOP) Page 37
Output:Hello

3) Using fully qualified name

If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.

It is generally used when two packages have same class name e.g. java.util and java.sql packages
contain Date class.

Example of package by import fully qualified name

//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
class B
{
public static void main(String args[])
{
pack.A obj = new pack.A(); //using fully qualified name
obj.msg();
}
}
Output:Hello

Handling name conflicts

 We can define two classes with the same name in different packages.

For example both, java.util and java.sql packages have a class named Date.
So if we import both packages in program as follows:

import java.util.*;
import java.sql.*;

//And then use Date class , then we will get a compile time error :

Date today ; //ERROR-- java.util.Date or java.sql.Date?

CS3391 UNIT2( OOP) Page 38


 The compiler will not be able to figure out which Date class do we want. This problem can
be solved by using specific import statement:

import java.util.Date;
import java.sql.*;
 If we need both Date classes then , we need to use full package name every time we declare
new object of that class.

For Example:
java.util.Date deadLine = new java.util.Date();
java.sql.Date today = new java.sql.Date();

Advantage of Java Package


1) Java package is used to categorize the classes and interfaces so that they can be easily maintained.
2) Java package provides access protection.
3) Java package removes naming collision.

13.Interfaces
An interface is a reference type in Java. It is similar to class. It is a collection of abstract methods.
A class implements an interface, thereby inheriting the abstract methods of the interface.
 The interface in java is a mechanism to achieve abstraction.
 Java Interface also represents IS-A relationship.
 It cannot be instantiated just like abstract class.
There are mainly three reasons to use interface. They are given below.
 It is used to achieve abstraction.
 Since java does not support multiple inheritance, by interface we can support the
functionality of multiple inheritance.
 It can be used to achieve loose coupling.
Defining (Declaring) Interfaces:
The interface keyword is used to declare an interface. Here is a simple example to declare an
interface .

Syntax:
interface <interface_name>
{
// declare constant fields
// declare methods that are
abstract by default.
}

Example:
interface Player
{

CS3391 UNIT2( OOP) Page 39


final int id = 10;
int move();
}

 An interface is implicitly abstract. You do not need to use the abstract keyword while
declaring an interface.
 Each method in an interface is also implicitly abstract, so the abstract keyword is not needed.
 Methods in an interface are implicitly public.

Internal addition by compiler


Interface fields are public, static and final by default, and methods are public and abstract.

The java compiler adds public and abstract keywords before the interface method. More, it adds
public, static and final keywords before data members.

Implementing interface
 A class uses the implements keyword to implement an interface.
 A class can implement more than one interface, so the implements keyword is followed by a
comma-separated list of the interfaces implemented by the class.
Syntax:
class classname implements interfacename
{
// variable declaration
// method declaration
}
Example1:
interface MyInterface
{
public void method1();
public void method2();
}
class Demo implements MyInterface
{
public void method1()
{
System.out.println("implementation of method1");
}
public void method2()
{
System.out.println("implementation of method2");

CS3391 UNIT2( OOP) Page 40


}
public static void main(String arg[])
{
MyInterface obj = new Demo();
obj.method1();
}
}
Output:
implementation of method1

Differences between classes and interfaces


classes interfaces
1. A class is instantiated to create objects. 1. An interface can never be instantiated
2. The members of a class can be private, public or 2. The members of an interface are always
protected. public.
3. It should contain only concrete methods 3. The methods in an interface are purely
(methods with body) abstract. (methods without body)
4. A class can extend only one class but it 4. An interface can extend multiple
implement any number of interfaces. interfaces but it cannot implement any
interface.
5. A class can have constructors to initialize the 5. An interface can never have a constructor
variables.
6. "extends" keyword should be used to inherit 6. "implements" keyword should be used to
inherit
7. Methods can be final and static 7. Methods should not be final and static
8. Variables can be private 8. Variables should be public only
9. It Can have constructors 9. It Cannot have constructors
10. It Cannot have main() method as main()
10. It Can have main() method is a concrete method

Understanding relationship between classes and interfaces


A class extends another class, an interface extends another interface but a class implements an
interface.

Extending interfaces
One interface can inherit another interface by use of the keyword “extends”. The syntax is the same
as for inheriting classes.
An interface can extend another interface in the same way that a class can extend another class.

CS3391 UNIT2( OOP) Page 41


The extends keyword is used to extend an interface, and the child interface inherits the methods of
the parent interface.
SYNTAX
interface InterfaceName extends interfacel
{
//interface body
}
Example:
public interface DriveCar
{
void turnLeft();
void turnRight();
void moveBack();
}

interface maruthicar extends DriveCar


{
void accelerate();
}
Example2:(EXTENDING AN INTERFACE)
interface Inf1
{
public void method1();
}
interface Inf2 extends Inf1
{
public void method2();
}
public class Demo implements Inf2
{
/* Even though this class is only implementing the interface Inf2, it has to implement
all the methods of Inf1 as well because the interface Inf2 extends Inf1 */
public void method1()
{
System.out.println("method1 in interface1");
}
public void method2()
{
System.out.println("method2 in interface2");
}
public static void main(String args[])
{
Demo obj = new Demo();
obj.method2();
}
}
Output:
method2 in interface2

CS3391 UNIT2( OOP) Page 42


Class implements Interface
A class can implement any number of interfaces.
Example1(IMPLEMENTING AN INTERFACE)

import java.io.*;
interface shape
{
abstract public double area();
}
class circle implements shape
{
int r=50;
public double area()
{
return 3.14*r*r;
}
}
class rectangle implements shape
{
int l=50,b=40;
public double area()
{
return l*b;
}
}
class triangle implements shape
{
int b=50,h=40;
public double area()
{
return 0.5*b*h;
}
}
class shapeinterfacedemo
{
public static void main(String args[])
{
double result;
circle c=new circle();
result=c.area();
System.out.println("The Area is"+result);
rectangle r =new rectangle();
result=r.area();
System.out.println("The Area is"+result);
triangle t=new triangle();
result=t.area();
System.out.println("The Area is"+result);
}
}

CS3391 UNIT2( OOP) Page 43


OUTPUT

Z:\javafiles>javac shapeinterfacedemo.java
Z:\javafiles>java shapeinterfacedemo
The Area is7850.0
The Area is2000.0
The Area is1000.0

Why do we use an Interface?


1. Provides communication − One of the uses of the interface is to provide communication.
Through interface you can specify how you want the methods and fields of a particular type.
2. Multiple inheritance − Java doesn’t support multiple inheritance, using interfaces you can
achieve multiple inheritance
3. Abstraction − Abstraction is a process of hiding the implementation details from the user,
only the functionality will be provided to the user. In other words, the user will have the
information on what the object does instead of how it does it.
Interfaces are used to implement abstraction
4. Loose coupling − Coupling refers to the dependency of one object type on another, if two
objects are completely independent of each other and the changes done in one doesn’t affect
the other both are said to be loosely coupled.
You can achieve loose coupling in Java using interfaces

Multiple inheritance in Java by interfaces


If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known as
multiple inheritance.

Example

interface BikeI
{
int speed=50;
public void totalDistance();
}
interface CycleI
CS3391 UNIT2( OOP) Page 44
{
int distance=150;
public void speed();
}
public class TwoWheeler implements BikeI,CycleI
{
int totalDistance;
int avgSpeed;
public void totalDistance()
{
totalDistance=speed*distance;
System.out.println("Total Distance Travelled : "+totalDistance);
}
public void speed()
{
int avgSpeed=totalDistance/speed;
System.out.println("Average Speed maintained : "+avgSpeed);
}
public static void main(String args[])
{
TwoWheeler t1=new TwoWheeler();
t1.totalDistance();
t1.speed();
}
}
Output
Total Distance Travelled: 7500
Average Speed maintained: 150

CS3391 UNIT2( OOP) Page 45

You might also like