Unit II
Unit II
Overloading Methods
Definition: In Java, Method Overloading allows different methods to have the same name,
but different signatures where the signature can differ by the number of input parameters or
type of input parameters, or a mixture of both.
Example:
Example of Method Overloading Output
public class Sum { 30
public int sum(int x, int y) { return (x + y); } 60
31.0
public int sum(int x, int y, int z)
{
return (x + y + z);
}
class GFG {
public static void main(String[] args)
{
// Method 2
public void StudentId(int roll_no, String name)
{
System.out.println("Roll-No :" + roll_no + " " + "Name :" +
name);
}
}
class GFG {
// Main function
public static void main(String[] args)
{
Student obj = new Student();
obj.StudentId("Spyd3r", 1);
obj.StudentId(2, "Kamlesh");
}
}
Object as Parameters
Java is strictly pass-by-value. But the scenario may change when the parameter
passed is of primitive type or reference type.
o If we pass a primitive type to a method, then it is called pass-by-value or call-
by- value.
o If we pass an object to a method, then it is called pass-by-reference or call-by-
reference.
Object as a parameter is a way to establish communication between two or more
objects of the same class or different class as well.
Java Program to demonstrate Object as a Parameter Output
public class ObjDemo { F:\test>javac ObjDemo.java
F:\test>java Demo
int height;
The area is 276
int width;
ObjDemo(int h,int w)
height=h;
width=w;
void area(ObjDemo o)
class Demo {
obj1.area(obj2);
}}
Returning Objects
We can return an object from a method. The data type for such method is a class type.
Example Program Output
public class Sample Value : 20
{
private int value;
public Sample(int i)
{
value = i;
}
/**
* The makeTwice method returns a Sample
object
* containing the value twice the passed to it.
*/
public Sample makeTwice()
{
Sample temp = new Sample(value * 2);
return temp;
}
Inheritance: Basics
Definition: Inheritance is a mechanism in Java by which derived class can
borrow the properties of base class and at the same time the derived class may
have some additional properties.
Advantages of Inheritance
One of the key benefits of inheritance is to minimize the amount of duplicate code in an
application by sharing common code amongst several subclasses.
1. Reusability: The base class code can be used by derived class without any need to
rewrite the code.
2. Extensibility: The base class logic can be extended in the derived classes.
3. Data hiding: Base class can decide to keep some data private so that it cannot be
altered by the derived class.
4. Overriding: With inheritance, we will be able to override the methods of the base
class so that meaningful implementation of the base class method can be designed in the
derived class
The inheritance is a mechanism in which the child class is derived from a parent class.
This derivation is using the keyword extends.
The parent class is called base class and child class is called derived class.
For example
Class A
This is Base class
{
………
}
Class B extends A
This is Derived class
{
……….// uses properties of A
}
Types of Inheritance
1. Single Inheritance
2. Multi-level Inheritance
3. Hierarchical Inheritance
4. Multiple Inheritance
………..
}
public class B extends A{
……….
}
Multilevel Inheritance public class A{………………………….}
public class B extends A{…………….}
public class C extends B{……………}
Hierarchical Inheritance public class A{………………………….}
public class B extends A{…………….}
public class C extends A{……………}
Single Inheritance
In single inheritance there is one parent per derived class.
This is most common form of inheritance.
Multi-level Inheritance
When a derived class is derived from a base class which itself is a derived class then
that type of inheritance is called multilevel inheritance.
Hierarchical Inheritance
If a number of classes are derived from a single base class, it is called hierarchical
inheritance.
class Parent1 {
class Parent2 {
void fun() {
Method Overriding
If the same method is defined in both the superclass and the subclass, then the method
of the subclass class overrides the method of the superclass. This is known as method
overriding.
Rules for Method Overriding in Java
o The method name should be common and the same as it is in the parent
class.
o The method signature (parameter list, return type) in the method must be
the same as in the parent class.
o There must be an inheritance connection between classes.
o If it declared the methods as static or final, then those methods cannot be
overridden.
Example Program for Method Overriding Output
class Parent{ CHILD METHOD
void display()
{
System.out.println("PARENT METHOD");
}
}
class Child extends Parent
{
void display()
{
System.out.println("CHILD METHOD");
}
}
class Override{
public static void main(String args[]){
Child c=new Child();
c.display();
}
}
Example Program for Method Overriding using Output
super class
class Parent{ D:\java1>javac Override.java
void display()
{ D:\java1>java Override
System.out.println("PARENT METHOD"); PARENT METHOD
} CHILD METHOD
}
class Child extends Parent
{
void display()
{
super.display();
System.out.println("CHILD METHOD");
}
}
class Override{
public static void main(String args[]){
Child c=new Child();
c.display();
}
}
Java Program for Method Overriding Output
class A value of a:15
{ value of b:20
int a=0;
void fun(int i) The value of c= 300
{
this.a=i;
}
}
class B extends A
{
int b;
void fun(int i)
{
int c;
b=20;
super.fun(i+5);
System.out.println("value of a:"+a);
System.out.println("value of b:"+b);
c=a*b;
System.out.println("The value of c= "+c);
}
}
class OverrideDemo
{
public static void main(String args[])
{
B obj_B =new B();
obj_B.fun(10);//function re-defined in derived class
}
}
In above program, there are two class - class A and class B. The class A acts as a
superclass and the class B acts as a subclass. In class A, a method fun is defined in which
the variable a is assigned with some value. In the derived class B, we use the same function
name fun in which, we make use of super keyword to access the variable a and then it is
multiplied by b and the result of multiplication will be printed.
Super Keyword
Super is a keyword used to access the immediate parent class from subclass
There are three ways by which the keyword super is used.
1. The super () is used to invoke the class variable of immediate parent class.
Program Output
class A 10
{
int x=10;
}
class B extends A
{
int x=20;
void display()
{
System.out.println(super.x);
}
public static void main(String args[])
{
B obj =new B();
obj.display();
}
}
2. The super () is used to access the class method of immediate parent class.
Program Output
class A Method: Class A
{
void fun()
{
System.out.println("Method: Class A");
}
}
class B extends A
{
void fun()
{
System.out.println("Method: Class B");
}
void display()
{
super.fun();
}
public static void main(String args[])
{
B obj =new B(); obj.display();
}
}
Abstract Classes
A class which is declared with the abstract keyword is known as an abstract class in
Java. It can have abstract and non-abstract methods (method with the body).
Rules for Abstract Classes
o An abstract class must be declared with an abstract keyword.
o It can have abstract and non-abstract methods.
o It cannot be instantiated.
o It can have constructors and static methods also.
o It can have final methods which will force the subclass not to change the body
of the method.
void show()
{
System.out.println("Class B");
}
}
class AbstractMain
{
public static void main(String args[])
{
C obj=new C();
obj.display();
obj.show();
}
}
Packages
Pack1.java
import pack.PackDemo;
class Pack1
{
public static void main(String args[])
{
PackDemo obj=new PackDemo();
obj.show();
}
}
Accessing Packages
There are three ways to access the package from outside the package.
1. import package.*;
2. import package.classname;
3. fully qualified name.
1) Using packagename.*
The import keyword is used to make the classes and interface of another package accessible
to the current package.
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();
}
}
Output: Hello
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.
package pack;
public class A{
//save by B.java
package mypack;
class B{
obj.msg();
Output: Hello
Interfaces
interface <interface_name>{
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
Implementing Interfaces
Definition: Multiple inheritance is a mechanism in which the child class inherits the
properties from more than one parent classes.
Java does not support multiple inheritance because it creates ambiguity when the
properties from both the parent classes are inherited in child class or derived class. But it is
supported in case of interface because there is no ambiguity as implementation is provided by
the implementation class.
Test.java:10: fun() in Test1 cannot override fun() in Test; overridden method is final final
void fun() absido bene
1 error
Program Explanation
The above program, on execution shows the error. Because the method fun is declared
with the keyword final and it cannot be overridden in derived class.
The dynamic method dispatch is also called as runtime polymorphism. During the run time
polymorphism, a call to overridden method is resolved at run time. The overridden method is
called using the reference variable of a super class(or base class). The determination of which
method to invoke is done using the object being referred by the reference variable.
Following is a simple Java program that illustrates the Run time polymorphism.
class Base
void display()
{
public static void main(String args[])
Base obj=new Derived();//obj is reference to base class // which is referred by the derived
class
Output
D:\test>javac RunPolyDemo.java
D:\test>java RunPolyDemo
Program Explanation:
In above program, the display method is an overridden method because with the same
signature we are modifying it in its derived class. This method is invoked in the main ().
function using the reference obj. This reference variable is of superclass type. It is assigned
with the reference of Derived class. At run time it is decided that the display method of
derived class should be invoked. Hence it is known as run time polymorphism.