0% found this document useful (0 votes)
337 views46 pages

CS3391 OOPS Unit 2

This document provides an overview of topics covered in Unit 2 of the CS3391 Object Oriented Programming course, including method overloading, objects as parameters, returning objects, inheritance basics and types, the super keyword, method overriding, abstract classes, packages, interfaces, and importing packages. Key concepts covered are method overloading by changing number/type of arguments, passing objects as parameters which pass a reference rather than copy, returning objects from methods by returning the object type, inheritance and method overriding which provides specific implementation of a method in the subclass, and dynamic method dispatch which resolves overridden methods at runtime.

Uploaded by

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

CS3391 OOPS Unit 2

This document provides an overview of topics covered in Unit 2 of the CS3391 Object Oriented Programming course, including method overloading, objects as parameters, returning objects, inheritance basics and types, the super keyword, method overriding, abstract classes, packages, interfaces, and importing packages. Key concepts covered are method overloading by changing number/type of arguments, passing objects as parameters which pass a reference rather than copy, returning objects from methods by returning the object type, inheritance and method overriding which provides specific implementation of a method in the subclass, and dynamic method dispatch which resolves overridden methods at runtime.

Uploaded by

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

CS3391-OBJECT ORIENTED

PROGRAMMING
UNIT 2
INHERITANCE, PACKAGES & INTERFACES
by
S.Sakkaravarthi, AP/IT
Ramco Institute of Technology, Rajapalayam
UNIT 2-TOPICS

 Overloading Methods
 Objects as Parameters
 Returning Objects
 Static, Nested and Inner Classes
 Inheritance: Basics-Types of Inheritance
 Super keyword
UNIT 2-TOPICS

 Method Overriding-Dynamic Method Dispatch


 Abstract Classes-final with Inheritance
 Packages and Interfaces: Packages
 Packages and Member Access
 Importing Packages
 Interfaces
Overloading Methods

When a class has more than one method having the same
name but with different parameter lists, this feature is
called method overloading in Java.

There are two ways to overload the method in java:

1.By Changing number of arguments


2.By Changing the data type
Method Overloading-By Changing no of arguments

class Adder public class Overloadingdemo


{ {
static int add(int a, int b) public static void main(String args[])
{ {
return a+b; //Compile Time Polymorhism
} System.out.println(Adder.add(10,5));
static int add(int a, int b, int c)
System.out.println(Adder.add(10,5,6));
{
}
return a+b+c;
} }
} Output: 15
21
Method Overloading-By Changing no of arguments

class Adder public class Overloadingdemo


{ {
int add(int a, int b) public static void main(String args[])
{ {
return a+b; Adder ar = new Adder();
} //Compile Time Polymorhism
int add(int a, int b, int c) System.out.println(ar.add(10,5));
{ System.out.println(ar.add(10,5,6));
return a+b+c; }
} }
} Output: 15
21
Method Overloading-By Changing data type of arguments

class Adder public class Overloadingdemo


{ {
static int add(int a, int b) public static void main(String args[])
{ {
return a+b; //Compile Time Polymorhism
} System.out.println(Adder.add(10,5));
static float add(float a, float b, float c) System.out.println(Adder.add(1.1,5.5,6.2)
{ );
return a+b+c; }
} }
}
Output: 15
12.8
Method Overloading-By Changing data type of arguments

class Adder public class Overloadingdemo


{ {
int add(int a, int b) public static void main(String args[])
{ {
return a+b; Adder ar = new Adder();
} //Compile Time Polymorhism
float add(float a, float b, float c) System.out.println(ar.add(10,5));
{ System.out.println(ar.add(1.1,5.5,6.2));
return a+b+c; }
} }
}
Output: 15
12.8
Benefits of Method Overloading
 Increases the readability of the program

 Provides flexibility to call the same method for different


types of data.
 Reduces the execution time because the binding is done in
compilation time itself.
 Use the code again, which saves memory
Objects as Parameters

 Like primitive types, Objects can be passed as parameters to


methods in Java.

 When passing an object as a parameter to a method, a reference


to the object is passed rather than a copy of the object itself.

 This means that any modifications made to the object within the
method will have an impact on the original object.
Object as Parameter
public class Student
{
private int rollno;
private String name;
public MyClass(int r, String n)
{
rollno = r;
name = n;
}
public void display(Student obj) // Method with object as parameter
{
System.out.println(“Roll no is:"+ obj.rollno);
System.out.println(“Name is:" + obj.name);
}
Object as Parameter-Contd…

public static void main(String[] args)


{
Student s1 = new Student(10, "Hello");
Student s2 = new Student(20, "World");
// Call the method with object as parameter
s1.display(s2);
}
}
Returning Objects
 A method can have the class name as its return type.
Therefore it must return the object of the exact class or its
subclass.
 Java methods can also return objects. A reference to the
object is returned when an object is returned from a method,
and the calling method can use that reference to access the
object.
Java Program - Returning Objects
class SumReturn
{ public class SumReturnDemo
private int a; {
public SumReturn(int i) { public static void main(String args[])
a=i; } {
public SumReturn addition( ) SumReturn obj1=newSumReturn(50);
{ SumReturn obj2;
SumReturn result = new SumReturn(a + 100); obj2=obj1.addition();
obj2.display();
return result; }
} } }
public void display( ){ Addition: 150
System.out.println(“Addition:”+a);
} }
Method Overriding
 Method Overriding refers to the ability of a subclass to
provide a specific implementation of a method that is
already defined in its super class.
 It allows a subclass to modify the behavior of an inherited
method from its superclass.

Rules for Method Overriding:


1.Method must have same name as in the parent class
2.Method must have same parameter as in the parent class
3.There must be IS-A relationship (inheritance)
class
class Bank{
Bank{ class Test{
int
int getRateOfInterest()
getRateOfInterest() {{ public static void main(String args[])
{
return
return 0;
0;
SBI sbi=new SBI();
}}
BOI boi=new BOI();
}}
System.out.println("SBIInterest"+sbi.getRateOfInterest());
class
class SBI
SBI extends
extends Bank{
Bank{ System.out.println("BOI Interest"+boi.getRateOfInterest());
int
int getRateOfInterest(){
getRateOfInterest(){ }
return
return 3;
3; }
}} Output:
Output:
}} SBI
SBI INTEREST:3
INTEREST:3

class
class BOI
BOI extends
extends Bank{
Bank{ BOI
BOI INTEREST:4
INTEREST:4

int
int getRateOfInterest(){
getRateOfInterest(){
return
return 4;
4;
}}
}}
Method Overloading Vs Method Overriding
Method Overloading Method Overriding
Method overloading is performed within Method overriding occurs in two classes
class. that have IS-A relationship.
In Method Overloading, parameter must be In Method Overriding, parameter must
different. be same.

Return type can be same or different in Return type must be same in method
method overloading overriding
Method overloading is used to increase the Method overriding is used to provide the
readability of the program. specific implementation of the method that
is already provided by its superclass.
Method overloading is the example of Method overriding is the example of run
compile time polymorphism time polymorphism
Method Overloading Method Overriding

class Overloadingexample class Animal


{ {
int add(int a, int b) void eat()
{ {
return a+b; System.out.println(“ eating”);
} }
int add(int a,int b, int c) }
{ class Dog
return a+b+c; {
} void eat()

} {
System.out.println(“flush eating animal”);
}}
Dynamic Method Dispatch
 Dynamic Method Dispatch is the process by which a call to
an overridden method is resolved at run time (during code
execution).
 The concept of method overriding is the way to attain
runtime polymorphism in java.
 During the code execution, JVM decides which
implementation of the same method should be called.
 Dynamic Method Dispatch is another name for Runtime
Polymorphism.
Abstract Class
 A class that is declared with the abstract keyword is known
as abstract class in java.
 It can have abstract and non-abstract methods.
 An abstract method is a method that is declared without any
implementation.
 Abstract class needs to be extended and its method
implemented.
 Abstract class cannot be instantiated (i.e., Object cannot be
created for an abstract class).
Abstract Class-Syntax
abstract class <class name>
{
//abstract method and non-abstract methods
}
Abstract Method: A method which is declared as abstract and
does not have implementation is known as an abstract method
Abstract Method Syntax:

abstract return type method name(parameter list);


Final with Inheritance
In Java, the final keyword is used to restrict the user. The java final
keyword can be used in many context.
 Final variables: When a variable is declared as final, its value cannot be
changed once it has been initialized. This is useful for declaring constants
or other values that should not be modified.

 Final methods: When a method is declared as final, it cannot be


overridden by a subclass.

 Final classes: When a class is declared as final, it cannot be extended by a


subclass.
Final Variable
When a variable is declared as final, its value cannot be changed once it
has been initialized. This is useful for declaring constants or other
values that should not be modified.

class Bike class Test


{ {
final int speedlimit=90; //final variable Public static void main(String args[])
void run() {
{ Bike b =new Bike();
speedlimit=400; //value cannot be changed b.run();
System.out.println(“Speedlimit is”+Speedlimit); }
} }
}
Using Final to prevent Inheritance
When a class is declared as final then it cannot be subclassed i.e. no other
class can extend it. This is particularly useful, for example, when creating an
immutable class like the predefined String class. Declaring a class as final
implicitly declares all of its method as final.
final class A
{
// methods and fields
}
// The following class is illegal.
class B extends A
{
// ERROR! Can't subclass A
}
Using Final to prevent Overriding
When a method is declared as final then it cannot be overridden by
subclasses.
For example, The Object class does this, a number of its methods are final.

class A class B extends A


{ {
final void msg() void msg()
{ {
System.out.println(“This is final method”); // can’t Override final method in subclass
} }
} }
Packages and Interfaces: Packages
 A package is a collection of similar types of sub-packages,
interfaces and classes.

 In java, there are two types of packages:


i) Built-in Packages
ii) User-defined Packages

 package keyword is used in java to create packages:


Syntax:
package package-name;
Built-in Packages
 These packages consist of a large number of classes which
are a part of java API. Commonly used packages are
1) java.lang package contains language support classes
(which defines primitive types, math operations). This
package is automatically imported.
2) java.io package contains classes for supporting
input/output operations
3) java.util package contains utility classes like Scanner,
Date/Time etc..
Built-in Packages
4) java.applet package contains classes for creating Applets.

5) java.awt package contains classes for implementing the


components for GUI like button, menus etc.,

6) java.net package contain classes for supporting network


operations
User defined Packages
 User defined packages are those that developers create to
incorporate different needs of applications. In Simple terms,
User-defined packages are those that the user defines.
Sub Package
Packages that are defined inside another package is
called subpackage. These are not imported by default, they have
to imported explicitly.
Example:

import java.util.*;
Here, util is a sub-package created inside java package.
Packages and Member Access
Members private default protected public
of Java
class N Y N Y
variable Y Y Y Y
method Y Y Y Y
constructor Y Y Y Y
interface N Y N Y
Packages and Member Access
Access within within outside package outside
Modifier class package by subclass only package

private Y N N N

default Y Y N N

protected Y Y Y N

public Y Y Y Y
Private-Access Specifier

The Private access modifier is accessible only within the class. It


cannot be accessed from outside the class.
Example:

Create two classes A and Simple. The class A contains private


data member and private method. When accessing these private
members from outside the class (i.e. Simple) , compile-time error will
occur.
Example Program-Private Access Specifier

class A public class Simple


{ {
private int data=40; public static void main(String args[])
private void msg() {
{ A obj=new A();
System.out.println("Hello java"); //Compile Time Error
} System.out.println(obj.data);
} obj.msg();//Compile Time Error
}
}
Default-Access Specifier

 The default modifier is accessible only within package. It


cannot be accessed from outside the package. It provides
more accessibility than private. But, it is more restrictive than
protected, and public.
 If no access modifier is specified, then it is treated as default
modifier
Default-Access Specifier
In this program, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.

//save by B.java
//save by A.java
package mypack;
package pack;
import pack.*;
class A
class B
{
{
void msg()
public static void main(String args[])
{
{
System.out.println("Hello");
A obj=new A(); //Compile Time Error
}
obj.msg(); //Compile Time Error
}
}
}
Protected -Access Specifier
The protected access specifier is accessible within package and
outside the package but through inheritance only.
//save by B.java
//save by A.java
package mypack;
package pack;
import pack.*;
public class A
class B extends A
{
{
protected void msg()
public static void main(String args[])
{
{
System.out.println("Hello");
B obj=new B();
}
obj.msg(); Output: Hello
}
}
}
Public -Access Specifier
The public access specifier is accessible everywhere. It has
the widest scope among all other modifiers.
//save by B.java
//save by A.java
package mypack;
package pack;
import pack.*;
public class A
class B
{
{
public void msg()
public static void main(String args[])
{
{
System.out.println("Hello");
A obj=new A();
}
obj.msg(); Output: Hello
}
}
}
Advantages of Packages

 Java package is used to categorize the classes and


interfaces so that they can be easily maintained.
 Java package provides access protection
 Java package removes naming collision
Importing Packages
 The import keyword is used to access all members of a
package using the following statements.

1. import package.*
2. import package.classname
3. fully qualified name
Interfaces
 An interface in java is a blueprint of a class. It has static
constants and abstract methods. The interface in java is a
mechanism to achieve abstraction.

 There can be only abstract methods in the java interface, not


method body. It is used to achieve abstraction and multiple
inheritance in java.
Syntax-Interfaces
interface <interface-name>
{
//declare constant fields
//declare methods that abstract by default
}
Interfaces
Interface-Java Program

interface Printable public static void main(String args[])


{ {
int MIN=5; A obj = new A();
void print(); obj.print();
} }
class A implements Printable
}
{
public void print() OUTPUT:
{
System.out.println(“value:”+MIN); Value: 5
}
Advantages of Interfaces

 Interfaces are used to achieve multiple inheritance.


 Interfaces can be used to enforce a contract-that is a
specification that classes must implement certain
methods if they want to use that interface.
References
1. www.javatpoint.com

You might also like