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.
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.