SlideShare a Scribd company logo
1 of 45
Inheritance, Packages and Interfaces
UNIT 2
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
public class Overloadingdemo
{
public static void main(String args[])
{
//Compile Time Polymorhism
System.out.println(Adder.add(10,5));
System.out.println(Adder.add(10,5,6));
}
}
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static int add(int a, int b, int c)
{
return a+b+c;
}
}
Output: 15
21
Method Overloading-By Changing no of arguments
Method Overloading-By Changing no of arguments
public class Overloadingdemo
{
public static void main(String args[])
{
Adder ar = new Adder();
//Compile Time Polymorhism
System.out.println(ar.add(10,5));
System.out.println(ar.add(10,5,6));
}
}
class Adder
{
int add(int a, int b)
{
return a+b;
}
int add(int a, int b, int c)
{
return a+b+c;
}
}
Output: 15
21
public class Overloadingdemo
{
public static void main(String args[])
{
//Compile Time Polymorhism
System.out.println(Adder.add(10,5));
System.out.println(Adder.add(1.1,5.5,6.2)
);
}
}
class Adder
{
static int add(int a, int b)
{
return a+b;
}
static float add(float a, float b, float c)
{
return a+b+c;
}
}
Output: 15
12.8
Method Overloading-By Changing data type of arguments
public class Overloadingdemo
{
public static void main(String args[])
{
Adder ar = new Adder();
//Compile Time Polymorhism
System.out.println(ar.add(10,5));
System.out.println(ar.add(1.1,5.5,6.2));
}
}
class Adder
{
int add(int a, int b)
{
return a+b;
}
float add(float a, float b, float c)
{
return a+b+c;
}
}
Output: 15
12.8
Method Overloading-By Changing data type of arguments
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.
public class SumReturnDemo
{
public static void main(String args[])
{
SumReturn obj1=newSumReturn(50);
SumReturn obj2;
obj2=obj1.addition();
obj2.display();
}
}
class SumReturn
{
private int a;
public SumReturn(int i) {
a=i; }
public SumReturn addition( )
{
SumReturn result = new SumReturn(a + 100);
return result;
} }
public void display( ){
System.out.println(“Addition:”+a);
} }
Addition: 150
Java Program - Returning Objects
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 Test{
public static void main(String args[])
{
SBI sbi=new SBI();
BOI boi=new BOI();
System.out.println("SBIInterest"+sbi.getRateOfInterest());
System.out.println("BOI Interest"+boi.getRateOfInterest());
}
}
Output:
SBI INTEREST:3
BOI INTEREST:4
class Bank{
int getRateOfInterest() {
return 0;
}
}
class SBI extends Bank{
int getRateOfInterest(){
return 3;
}
}
class BOI extends Bank{
int getRateOfInterest(){
return 4;
}
}
Method Overloading Vs Method Overriding
Method Overloading Method Overriding
Method overloading is performed within
class.
Method overriding occurs in two classes
that have IS-A relationship.
In Method Overloading, parameter must be
different.
In Method Overriding, parameter must
be same.
Return type can be same or different in
method overloading
Return type must be same in method
overriding
Method overloading is used to increase the
readability of the program.
Method overriding is used to provide the
specific implementation of the method that
is already provided by its superclass.
Method overloading is the example of
compile time polymorphism
Method overriding is the example of run
time polymorphism
Method Overloading Method Overriding
class Overloadingexample
{
int add(int a, int b)
{
return a+b;
}
int add(int a,int b, int c)
{
return a+b+c;
}
}
class Animal
{
void eat()
{
System.out.println(“ eating”);
}
}
class Dog
{
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 Syntax:
abstract return type method name(parameter list);
Abstract Method: A method which is declared as abstract and
does not have implementation is known as an abstract method
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
{
final int speedlimit=90; //final variable
void run()
{
speedlimit=400; //value cannot be changed
System.out.println(“Speedlimit is”+Speedlimit);
}
}
class Test
{
Public static void main(String args[])
{
Bike b =new Bike();
b.run();
}
}
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
{
final void msg()
{
System.out.println(“This is final method”);
}
}
class B extends A
{
void msg()
{
// 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
of Java
private default protected public
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
Modifier
within
class
within
package
outside package
by subclass only
outside
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
public class Simple
{
public static void main(String args[])
{
A obj=new A();
//Compile Time Error
System.out.println(obj.data);
obj.msg();//Compile Time Error
}
}
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");
}
}
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
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj=new A(); //Compile Time Error
obj.msg(); //Compile Time Error
}
}
//save by A.java
package pack;
class A
{
void msg()
{
System.out.println("Hello");
}
}
In this program, the scope of class A and its method msg() is default so it cannot
be accessed from outside the package.
Protected -Access Specifier
//save by B.java
package mypack;
import pack.*;
class B extends A
{
public static void main(String args[])
{
B obj=new B();
obj.msg();
}
}
//save by A.java
package pack;
public class A
{
protected void msg()
{
System.out.println("Hello");
}
}
The protected access specifier is accessible within package and
outside the package but through inheritance only.
Output: Hello
Public -Access Specifier
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[])
{
A obj=new A();
obj.msg();
}
}
//save by A.java
package pack;
public class A
{
public void msg()
{
System.out.println("Hello");
}
}
The public access specifier is accessible everywhere. It has
the widest scope among all other modifiers.
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
public static void main(String args[])
{
A obj = new A();
obj.print();
}
}
interface Printable
{
int MIN=5;
void print();
}
class A implements Printable
{
public void print()
{
System.out.println(“value:”+MIN);
}
OUTPUT:
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.

More Related Content

Similar to UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces

packages and interfaces
packages and interfacespackages and interfaces
packages and interfacesmadhavi patil
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08Terry Yoast
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentSuresh Mohta
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteTushar B Kute
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10Terry Yoast
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...vekariyakashyap
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfBapanKar2
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in javaAhsan Raja
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance SlidesAhsan Raja
 
U2 JAVA.pptx
U2 JAVA.pptxU2 JAVA.pptx
U2 JAVA.pptxmadan r
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Javabackdoor
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaRadhika Talaviya
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIEduardo Bergavera
 

Similar to UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces (20)

packages and interfaces
packages and interfacespackages and interfaces
packages and interfaces
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
9781439035665 ppt ch08
9781439035665 ppt ch089781439035665 ppt ch08
9781439035665 ppt ch08
 
Basic concept of class, method , command line-argument
Basic concept of class, method , command line-argumentBasic concept of class, method , command line-argument
Basic concept of class, method , command line-argument
 
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B KuteChapter 02: Classes Objects and Methods Java by Tushar B Kute
Chapter 02: Classes Objects and Methods Java by Tushar B Kute
 
Chap11
Chap11Chap11
Chap11
 
Object oriented concepts
Object oriented conceptsObject oriented concepts
Object oriented concepts
 
9781439035665 ppt ch10
9781439035665 ppt ch109781439035665 ppt ch10
9781439035665 ppt ch10
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
 
Java defining classes
Java defining classes Java defining classes
Java defining classes
 
polymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdfpolymorphismpresentation-160825122725.pdf
polymorphismpresentation-160825122725.pdf
 
Polymorphism presentation in java
Polymorphism presentation in javaPolymorphism presentation in java
Polymorphism presentation in java
 
11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf11.Object Oriented Programming.pdf
11.Object Oriented Programming.pdf
 
Inheritance Slides
Inheritance SlidesInheritance Slides
Inheritance Slides
 
U2 JAVA.pptx
U2 JAVA.pptxU2 JAVA.pptx
U2 JAVA.pptx
 
OOPs & Inheritance Notes
OOPs & Inheritance NotesOOPs & Inheritance Notes
OOPs & Inheritance Notes
 
Object Oriented Programming with Java
Object Oriented Programming with JavaObject Oriented Programming with Java
Object Oriented Programming with Java
 
Classes, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with JavaClasses, Objects and Method - Object Oriented Programming with Java
Classes, Objects and Method - Object Oriented Programming with Java
 
Chapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part IIChapter 7 - Defining Your Own Classes - Part II
Chapter 7 - Defining Your Own Classes - Part II
 
Java basics
Java basicsJava basics
Java basics
 

More from SakkaravarthiS1

UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingSakkaravarthiS1
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...SakkaravarthiS1
 
UNIT-1 PPT.pptCS 3492 DBMS UNIT 1 to 5 overview Unit 1 slides including purpo...
UNIT-1 PPT.pptCS 3492 DBMS UNIT 1 to 5 overview Unit 1 slides including purpo...UNIT-1 PPT.pptCS 3492 DBMS UNIT 1 to 5 overview Unit 1 slides including purpo...
UNIT-1 PPT.pptCS 3492 DBMS UNIT 1 to 5 overview Unit 1 slides including purpo...SakkaravarthiS1
 
DATABASE MANAGEMENT SYSTEMS university course materials useful for students ...
DATABASE MANAGEMENT SYSTEMS  university course materials useful for students ...DATABASE MANAGEMENT SYSTEMS  university course materials useful for students ...
DATABASE MANAGEMENT SYSTEMS university course materials useful for students ...SakkaravarthiS1
 
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfUNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfSakkaravarthiS1
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesSakkaravarthiS1
 

More from SakkaravarthiS1 (6)

UNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and MultithreadingUNIT-3.pptx Exception Handling and Multithreading
UNIT-3.pptx Exception Handling and Multithreading
 
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
Unit-1 SQL fundamentals.docx SQL commands used to create table, insert values...
 
UNIT-1 PPT.pptCS 3492 DBMS UNIT 1 to 5 overview Unit 1 slides including purpo...
UNIT-1 PPT.pptCS 3492 DBMS UNIT 1 to 5 overview Unit 1 slides including purpo...UNIT-1 PPT.pptCS 3492 DBMS UNIT 1 to 5 overview Unit 1 slides including purpo...
UNIT-1 PPT.pptCS 3492 DBMS UNIT 1 to 5 overview Unit 1 slides including purpo...
 
DATABASE MANAGEMENT SYSTEMS university course materials useful for students ...
DATABASE MANAGEMENT SYSTEMS  university course materials useful for students ...DATABASE MANAGEMENT SYSTEMS  university course materials useful for students ...
DATABASE MANAGEMENT SYSTEMS university course materials useful for students ...
 
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdfUNIT 5-JavaFX Event Handling, Controls and Components.pdf
UNIT 5-JavaFX Event Handling, Controls and Components.pdf
 
UNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf NotesUNIT4-IO,Generics,String Handling.pdf Notes
UNIT4-IO,Generics,String Handling.pdf Notes
 

Recently uploaded

HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2RajaP95
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLDeelipZope
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...srsj9000
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort servicejennyeacort
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZTE
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx959SahilShah
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineeringmalavadedarshan25
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxbritheesh05
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝soniya singh
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxJoão Esperancinha
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escortsranjana rawat
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCall Girls in Nagpur High Profile
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130Suhani Kapoor
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVRajaP95
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Dr.Costas Sachpazis
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsCall Girls in Nagpur High Profile
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.eptoze12
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...VICTOR MAESTRE RAMIREZ
 

Recently uploaded (20)

HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2HARMONY IN THE HUMAN BEING - Unit-II UHV-2
HARMONY IN THE HUMAN BEING - Unit-II UHV-2
 
Current Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCLCurrent Transformer Drawing and GTP for MSETCL
Current Transformer Drawing and GTP for MSETCL
 
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
Gfe Mayur Vihar Call Girls Service WhatsApp -> 9999965857 Available 24x7 ^ De...
 
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort serviceGurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
Gurgaon ✡️9711147426✨Call In girls Gurgaon Sector 51 escort service
 
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
ZXCTN 5804 / ZTE PTN / ZTE POTN / ZTE 5804 PTN / ZTE POTN 5804 ( 100/200 GE Z...
 
Application of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptxApplication of Residue Theorem to evaluate real integrations.pptx
Application of Residue Theorem to evaluate real integrations.pptx
 
Internship report on mechanical engineering
Internship report on mechanical engineeringInternship report on mechanical engineering
Internship report on mechanical engineering
 
Artificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptxArtificial-Intelligence-in-Electronics (K).pptx
Artificial-Intelligence-in-Electronics (K).pptx
 
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
Model Call Girl in Narela Delhi reach out to us at 🔝8264348440🔝
 
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptxDecoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
Decoding Kotlin - Your guide to solving the mysterious in Kotlin.pptx
 
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Isha Call 7001035870 Meet With Nagpur Escorts
 
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Serviceyoung call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
young call girls in Rajiv Chowk🔝 9953056974 🔝 Delhi escort Service
 
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
9953056974 Call Girls In South Ex, Escorts (Delhi) NCR.pdf
 
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service NashikCollege Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
College Call Girls Nashik Nehal 7001305949 Independent Escort Service Nashik
 
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
VIP Call Girls Service Hitech City Hyderabad Call +91-8250192130
 
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IVHARMONY IN THE NATURE AND EXISTENCE - Unit-IV
HARMONY IN THE NATURE AND EXISTENCE - Unit-IV
 
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
Sheet Pile Wall Design and Construction: A Practical Guide for Civil Engineer...
 
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur EscortsHigh Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
High Profile Call Girls Nagpur Meera Call 7001035870 Meet With Nagpur Escorts
 
Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.Oxy acetylene welding presentation note.
Oxy acetylene welding presentation note.
 
Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...Software and Systems Engineering Standards: Verification and Validation of Sy...
Software and Systems Engineering Standards: Verification and Validation of Sy...
 

UNIT-2.pptx CS3391 Inheritance , types, packages and Interfaces

  • 1. Inheritance, Packages and Interfaces UNIT 2
  • 2. UNIT 2-TOPICS  Overloading Methods  Objects as Parameters  Returning Objects  Static, Nested and Inner Classes  Inheritance: Basics-Types of Inheritance  Super keyword
  • 3. UNIT 2-TOPICS  Method Overriding-Dynamic Method Dispatch  Abstract Classes-final with Inheritance  Packages and Interfaces: Packages  Packages and Member Access  Importing Packages  Interfaces
  • 4. 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
  • 5. public class Overloadingdemo { public static void main(String args[]) { //Compile Time Polymorhism System.out.println(Adder.add(10,5)); System.out.println(Adder.add(10,5,6)); } } class Adder { static int add(int a, int b) { return a+b; } static int add(int a, int b, int c) { return a+b+c; } } Output: 15 21 Method Overloading-By Changing no of arguments
  • 6. Method Overloading-By Changing no of arguments public class Overloadingdemo { public static void main(String args[]) { Adder ar = new Adder(); //Compile Time Polymorhism System.out.println(ar.add(10,5)); System.out.println(ar.add(10,5,6)); } } class Adder { int add(int a, int b) { return a+b; } int add(int a, int b, int c) { return a+b+c; } } Output: 15 21
  • 7. public class Overloadingdemo { public static void main(String args[]) { //Compile Time Polymorhism System.out.println(Adder.add(10,5)); System.out.println(Adder.add(1.1,5.5,6.2) ); } } class Adder { static int add(int a, int b) { return a+b; } static float add(float a, float b, float c) { return a+b+c; } } Output: 15 12.8 Method Overloading-By Changing data type of arguments
  • 8. public class Overloadingdemo { public static void main(String args[]) { Adder ar = new Adder(); //Compile Time Polymorhism System.out.println(ar.add(10,5)); System.out.println(ar.add(1.1,5.5,6.2)); } } class Adder { int add(int a, int b) { return a+b; } float add(float a, float b, float c) { return a+b+c; } } Output: 15 12.8 Method Overloading-By Changing data type of arguments
  • 9. 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
  • 10. 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.
  • 11. 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); }
  • 12. 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); } }
  • 13. 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.
  • 14. public class SumReturnDemo { public static void main(String args[]) { SumReturn obj1=newSumReturn(50); SumReturn obj2; obj2=obj1.addition(); obj2.display(); } } class SumReturn { private int a; public SumReturn(int i) { a=i; } public SumReturn addition( ) { SumReturn result = new SumReturn(a + 100); return result; } } public void display( ){ System.out.println(“Addition:”+a); } } Addition: 150 Java Program - Returning Objects
  • 15. 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)
  • 16. class Test{ public static void main(String args[]) { SBI sbi=new SBI(); BOI boi=new BOI(); System.out.println("SBIInterest"+sbi.getRateOfInterest()); System.out.println("BOI Interest"+boi.getRateOfInterest()); } } Output: SBI INTEREST:3 BOI INTEREST:4 class Bank{ int getRateOfInterest() { return 0; } } class SBI extends Bank{ int getRateOfInterest(){ return 3; } } class BOI extends Bank{ int getRateOfInterest(){ return 4; } }
  • 17. Method Overloading Vs Method Overriding Method Overloading Method Overriding Method overloading is performed within class. Method overriding occurs in two classes that have IS-A relationship. In Method Overloading, parameter must be different. In Method Overriding, parameter must be same. Return type can be same or different in method overloading Return type must be same in method overriding Method overloading is used to increase the readability of the program. Method overriding is used to provide the specific implementation of the method that is already provided by its superclass. Method overloading is the example of compile time polymorphism Method overriding is the example of run time polymorphism
  • 18. Method Overloading Method Overriding class Overloadingexample { int add(int a, int b) { return a+b; } int add(int a,int b, int c) { return a+b+c; } } class Animal { void eat() { System.out.println(“ eating”); } } class Dog { void eat() { System.out.println(“flush eating animal”); } }
  • 19. 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.
  • 20. 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).
  • 21. Abstract Class-Syntax abstract class <class name> { //abstract method and non-abstract methods } Abstract Method Syntax: abstract return type method name(parameter list); Abstract Method: A method which is declared as abstract and does not have implementation is known as an abstract method
  • 22. 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.
  • 23. 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 { final int speedlimit=90; //final variable void run() { speedlimit=400; //value cannot be changed System.out.println(“Speedlimit is”+Speedlimit); } } class Test { Public static void main(String args[]) { Bike b =new Bike(); b.run(); } }
  • 24. 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 }
  • 25. 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 { final void msg() { System.out.println(“This is final method”); } } class B extends A { void msg() { // can’t Override final method in subclass } }
  • 26. 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;
  • 27. 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..
  • 28. 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
  • 29. 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.
  • 30. 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.
  • 31. Packages and Member Access Members of Java private default protected public 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
  • 32. Packages and Member Access Access Modifier within class within package outside package by subclass only outside package private Y N N N default Y Y N N protected Y Y Y N public Y Y Y Y
  • 33. 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.
  • 34. Example Program-Private Access Specifier public class Simple { public static void main(String args[]) { A obj=new A(); //Compile Time Error System.out.println(obj.data); obj.msg();//Compile Time Error } } class A { private int data=40; private void msg() { System.out.println("Hello java"); } }
  • 35. 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
  • 36. Default-Access Specifier //save by B.java package mypack; import pack.*; class B { public static void main(String args[]) { A obj=new A(); //Compile Time Error obj.msg(); //Compile Time Error } } //save by A.java package pack; class A { void msg() { System.out.println("Hello"); } } In this program, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.
  • 37. Protected -Access Specifier //save by B.java package mypack; import pack.*; class B extends A { public static void main(String args[]) { B obj=new B(); obj.msg(); } } //save by A.java package pack; public class A { protected void msg() { System.out.println("Hello"); } } The protected access specifier is accessible within package and outside the package but through inheritance only. Output: Hello
  • 38. Public -Access Specifier //save by B.java package mypack; import pack.*; class B { public static void main(String args[]) { A obj=new A(); obj.msg(); } } //save by A.java package pack; public class A { public void msg() { System.out.println("Hello"); } } The public access specifier is accessible everywhere. It has the widest scope among all other modifiers. Output: Hello
  • 39. 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
  • 40. 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
  • 41. 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.
  • 42. Syntax-Interfaces interface <interface-name> { //declare constant fields //declare methods that abstract by default }
  • 44. Interface-Java Program public static void main(String args[]) { A obj = new A(); obj.print(); } } interface Printable { int MIN=5; void print(); } class A implements Printable { public void print() { System.out.println(“value:”+MIN); } OUTPUT: Value: 5
  • 45. 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.