Unit 2 2022
Unit 2 2022
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.
Z:\javafiles>java TestOverloading2
22
24.9
class Showclass
{
void show(int rollno, String name)
{
System.out.println("rollno"+ rollno);
System.out.println("name"+name);
}
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.
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.
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)
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.
}
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
obj2 = obj1.incrByTen(obj1);
}
}
OUTPUT:
obj1.a : 12
obj2.a : 22
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
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:
{
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[])
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:
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
class Demo
{
void show()
{
System.out.println("i am in show method of super class");
}
}
class Flavor1Demo
{
interface Hello
{
void show();
}
class Flavor2Demo
{
Output
i am in anonymous class
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).
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
}
}
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
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);
}
5.Types of Inheritance
1.Single Inheritance:
When a single class is derived from on single base class is known as single inheritance.
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.
Hierarchical Inheritance: When more than one class is derived from an existing class is known as
Hierarchical inheritance.
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.
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");
}
class D extends A
{
public void disp()
{
System.out.println("D");
}
public static void main(String args[]){
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.
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.
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...
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.
Dynamic method dispatch is the mechanism by which a call to an overridden method is resolved at
run time, rather than compile 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
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;
Output:
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()
class overridingdemo
{
public static void main(String[] args)
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).
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 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
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;
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
Abstract Method
An abstract method is a method that is declared without an implementation (without braces, and
followed by a semicolon), like this:
if a class includes abstract methods, then the class itself must be declared abstract, as in:
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.
{
System.out.println("Method of class Sum");
}
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.
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.
3) java.util: Contains utility classes which implement data structures like Linked List, Dictionary and
support ; for Date / Time operations.
5) java.awt: Contain classes for implementing the components for graphical user interfaces (like
button , ;menus etc).
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.
Creating a Package
//save as Simple.java
package mypack;
public class Simple
{
public static void main(String args[])
{
System.out.println("Welcome to package");
}
}
If you are not using any IDE, you need to follow the syntax given below:
For example
javac -d . Simple.java
You need to use fully qualified name e.g. mypack.Simple etc to run the class.
Output:Welcome to 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:
There are three ways to access the package from outside the package.
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.
//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
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.
//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
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 :
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();
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
{
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.
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");
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.
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);
}
}
Z:\javafiles>javac shapeinterfacedemo.java
Z:\javafiles>java shapeinterfacedemo
The Area is7850.0
The Area is2000.0
The Area is1000.0
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