UNIT II Oops
UNIT II Oops
UNIT II Oops
1. Overloading Methods
1. Explain briefly about function overloading with a suitable example.
Nov/Dec 2021
2. Outline Method overriding with an example. Nov/Dec 2021
When two or more methods within the same class that have the same name, but their
parameter declarations are different. The methods are said to be overloaded, and the
process is referred to as method overloading. Method overloading is one of the ways that
Java supports polymorphism.
Example:
void test() {
System.out.println("No parameters");
}
// Overload test for a double parameter double test(double a) { System.out.println("double
a: " + a); return a*a;
}
class Overload {
Output: No
parameters
a: 10 a and b: 10
20 double a:
123.25
Method Overriding
When a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within its subclass, it will always
refer to the version of that method defined by the subclass. The version of the method
defined by the superclass will be hidden.
Example:
int i, j;
A(int a, int b) { i = a;
j = b;
class Override {
public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this calls
show() in B
Output:
k: 3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A. If you
wish to access the superclass version of an overridden method, you can do so by using
super. For example, in this version of B, the superclass version of show( ) is invoked within
the subclass’ version. This allows all instance variables to be displayed. class B extends A
{ int k;
B(int a, int b, int c) { super(a,
b); k = c;
If you substitute this version of A into the previous program, you will see the following
Output:
i and j: 1 2
k: 3
Java does this interesting thing that’s sort of a hybrid between pass-by-value and pass-
byreference. Basically, a parameter cannot be changed by the function, but the function can
ask the parameter to change itself via calling some method within it.
• 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 callby-
reference.
• Changes to the object inside the method do reflect the object used as an argument.
Illustration: Let us suppose three objects ‘ob1’ , ‘ob2’ and ‘ob3’ are created:
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.
System.out.println("ob1 == ob2: " + ob1.equalTo(ob2));
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)
Again ‘o’ will reassign to ‘ob3’ as the following statement execute.
System.out.println("ob1 == ob3: " + ob1.equalTo(ob3));
• 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.
Example
// Class 1
class ObjectReturnDemo {
int a;
// Constructor
ObjectReturnDemo(int i)
{ a = i; }
// Class 2 //
Main class
public class GFG {
// Main driver method
public static void main(String args[])
{
ob2 = ob1.incrByTen();
Output ob1.a:
2 ob2.a: 12
Inner class means one class which is a member of another class. There are
basically four types of inner classes in java.
1)Static nested classes
2)Nested Inner class
3)Method Local inner classes
4)Anonymous inner classes
Static nested classes are not technically an inner class. They are like a static member of
outer class.
Example: class Outer { private static void outerMethod()
{ System.out.println("inside outerMethod");
}
// A static inner class static class Inner {
public static void main(String[] args)
{
System.out.println("inside inner class Method"); outerMethod();
}
}
}
Output:
inside inner class Method inside outerMethod
Nested Inner class can access any private instance variable of outer class. Like
any other instance variable, we can have access modifier private, protected, public
and default modifier. Like class, interface can also be nested and can have access
specifiers. Example:
class Outer {
// Simple
nested
inner class
class
Inner { public void
show() {
System.out.println("In a nested class method");
}
}
}
class Main {
public static void
main(String[] args)
{ Outer.Inner in = new
Outer().new Inner();
in.show();
}
}
Output:
In a nested class method
2.INHERITANCE
1.Explain in detail about various types of inheritance in java with neat diagram?
(NOV/DEC 2019)
3. Write a Java program to calculate electricity bill using inheritance. The program
should get the inputs of watts per hour and unit rate. Check your program for the
following case : Assume a consumer consumes 5000 watts per hour daily for one
month. Calculate the total energy bill of that consumer if per unit rate is 7 [1 unit =
1k Wh]. (NOV/DEC 2020)
4. Outline the use of extends keyword in Java with syntax. (NOV/DEC 2021)
5. When a class hierarchy is created, in what order are the constructors for the
classes that make up the hierarchy called? Outline with an example(NOV/DEC
2021)
6. Outline method overriding with an example. (NOV/DEC 2021)
In Single Inheritance one class extends another class (one class only).
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
public static void main(String args[])
{
//Assigning ClassB object
to ClassB reference ClassB b
= new ClassB(); //call
dispA() method of
ClassA
b.dispA();
//call dispB() method
of
ClassB
b.dispB();
}
}
Output :
disp() method of ClassA
disp() method of ClassB
MULTILEVEL INHERITANCE
In Multilevel Inheritance, one class can inherit from a derived class. Hence, the derived
class becomes the base class for the new class.
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassB
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
public static void main(String args[])
{
//Assigning ClassC object to ClassC reference ClassC c = new ClassC();
//call dispA() method of ClassA c.dispA();
//call dispB() method of ClassB c.dispB();
//call dispC() method of ClassC c.dispC();
}
}
Output :
disp() method of ClassA disp() method of ClassB disp() method of ClassC
HIERARCHICAL INHERITANCE
Example:
public class ClassA
{
public void dispA()
{
System.out.println("disp() method of ClassA");
}
}
public class ClassB extends ClassA
{
public void dispB()
{
System.out.println("disp() method of ClassB");
}
}
public class ClassC extends ClassA
{
public void dispC()
{
System.out.println("disp() method of ClassC");
}
}
public class ClassD extends ClassA
{
public void dispD()
{
System.out.println("disp() method of ClassD");
}
}
public class HierarchicalInheritanceTest
{
public static void main(String args[])
{
//Assigning ClassB object to ClassB reference
ClassB b = new ClassB();
//call dispB() method of ClassB b.dispB();
//call dispA() method of ClassA b.dispA();
//Assigning ClassC object to ClassC reference ClassC c = new ClassC();
//call dispC() method of ClassC c.dispC();
//call dispA() method of ClassA c.dispA();
Hybrid Inheritance is the combination of both Single and Multiple Inheritance. Again
Hybrid inheritance is also not directly supported in Java only through interface we can
achieve this. Flow diagram of the Hybrid inheritance will look like below. As you can
ClassA will be acting as the Parent class for ClassB & ClassC and ClassB & ClassC will be
acting as Parent for ClassD.
Multiple Inheritance is nothing but one class extending more than oneclass.Multiple
Inheritance is basically not supported by many Object Oriented Programming languages
such as Java, Small Talk, C# etc.. (C++SupportsMultiple Inheritance). As the Child class
has to manage the dependency of more than one Parent class. But you can achieve
multiple inheritance in Java using Interfaces.
1. super() invokes the constructor of the parent class super() will invoke the
constructor of the parent class. Even when you don’t add super() keyword the
compiler will add one and will invoke the Parent Class constructor.
Example:
class ParentClass
{
ParentClass()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
SubClass()
{
System.out.println("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}
}
Output:
Parent Class default Constructor Child Class default Constructor
Even when we add explicitly also it behaves the same way as it did before. class
ParentClass
{
public ParentClass()
{
System.out.println("Parent Class default Constructor");
}
}
public class SubClass extends ParentClass
{
SubClass()
{
super();
System.out.println("Child Class default Constructor");
}
public static void main(String args[])
{
SubClass s = new SubClass();
}
}
Output:
Parent Class default Constructor
Child Class default Constructor
You can also call the parameterized constructor of the Parent Class. For example,
super(10) will call parameterized constructor of the Parent class.
class ParentClass
{
ParentClass()
{
System.out.println("Parent Class default Constructor called");
}
ParentClass(int val)
{
System.out.println("Parent Class parameterized Constructor, value: "+val);
}
}
public class SubClass extends ParentClass
{
SubClass()
{
super();//Has to be the first statement in the constructor System.out.println("Child Class
default Constructor called");
}
SubClass(int val)
{
super(10);
System.out.println("Child Class parameterized Constructor, value: "+val);
}
public static void main(String args[])
{
}
}
Output
Parent Class default Constructor called Child Class default Constructor called Parent
Class parameterized Constructor, value: 10
Child Class parameterized Constructor, value: 10
void disp()
{
System.out.println("Value is : "+val);
}
}
}
Output
Value is : 123
This will call only the val of the sub class only. Without super keyword, you cannot call
the val
which is present in the Parent Class. class ParentClass
{
int val=999;
}
public class SubClass extends ParentClass
{
int val=123;
void disp()
{
System.out.println("Value is : "+super.val);
}
void disp()
{
System.out.println("Child Class method");
}
void show()
{ disp();
}
public static void main(String args[])
{
}
}
Output:
void show()
{
//Calling SubClass disp() method disp();
//Calling ParentClass disp() method super.disp();
}
public static void main(String args[])
{
}
}
Output
When there is no method overriding then by default Parent Class disp() method will be
called. class ParentClass
{
public void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
public void show()
{ disp();
}
public static void main(String args[])
{
SubClass s = new SubClass(); s.show(); }}
Output:
Parent Class method
2.2 Method Overriding
When a method in a subclass has the same name and type signature as a method in its
superclass, then the method in the subclass is said to override the method in the
superclass. When an overridden method is called from within its subclass, it will always
refer to the version of that method defined by the subclass. The version of the method
defined by the superclass will be hidden.
Example:
// Method overriding. class A { int
i, j;
A(int a, int b) { i = a;
j = b;
}
// display i and j void show() {
System.out.println("i and j: " + i + " " + j);
}
}
class B extends A { int k; B(int a,
int b, int c) { super(a, b); k = c;
}
// display k – this overrides show() in A void show() {
System.out.println("k: " + k);
}
}
class Override {
public static void main(String args[]) { B subOb = new B(1, 2, 3); subOb.show(); // this
calls show() in B
}
}
Output: k:
3
When show( ) is invoked on an object of type B, the version of show( ) defined within B is
used. That is, the version of show( ) inside B overrides the version declared in A. If you
wish to access the superclass version of an overridden method, you can do so by using
super. For example, in this version of B, the superclass version of show( ) is invoked
within the subclass’ version. This allows all instance variables to be displayed. class B
extends A {
int k;
B(int a, int b, int c) {
super(a, b); k = c;
}
void show() {
super.show(); // this calls A's show() System.out.println("k: " + k);
}
}
If you substitute this version of A into the previous program, you will see the following
Output:
i and j: 1 2
k: 3
Here, super.show( ) calls the superclass version of show( ).
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[])
{
// object of type A
A a = new A();
// object of type B
B b = new B();
// object of type C
C c = new C();
Output:
Inside A's m1 method Inside
B's m1 method
Inside C's m1 method
Explanation:
The above program creates one superclass called A and it’s two subclasses B and C. These
subclasses overrides m1( ) method.
1. Inside the main() method in Dispatch class, initially objects of type A, B, and C are declared.
2. A a = new A(); // object of type A
3. B b = new B(); // object of type B
4. C c = new C(); // object of type C
5. Now a reference of type A, called ref, is also declared, initially it will point to null. 6. A ref; //
obtain a reference of type A
7. 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.
8. ref = a; // r refers to an A object
9. ref.m1(); // calling A's version of m1()
ref = b; // now r refers to a B object ref.m1(); // calling B's version of m1()
A class that is declared with abstract keyword, is known as abstract class in java. It can
have abstract and non-abstract methods (method with body).Abstraction is a process of
hiding the implementation details and showing only functionality to the user.
Abstraction lets you focus on what the object does instead of how it does it. It needs to be
extended and its method implemented. It cannot be instantiated.
Example abstract class:
abstract class A{}
abstract method:
A method that is declared as abstract and does not have implementation is known as
abstract method.
abstract void printStatus();//no body and abstract
In this example, Shape is the abstract class, its implementation is provided by the
Rectangle and Circle classes.
If you create the instance of Rectangle class, draw() method of Rectangle class will be
invoked. Example1:
File: TestAbstraction1.java abstract class Shape{ abstract void draw();
}
//In real scenario, implementation is provided by others i.e. unknown by end user class
Rectangle extends Shape{
void draw(){System.out.println("drawing rectangle");}
}
class Circle1 extends Shape{
void draw(){System.out.println("drawing circle");}
}
//In real scenario, method is called by programmer or user class
TestAbstraction1{ public static void main(String args[]){
Shape s=new Circle1();//In real scenario, object is provided through method e.g.
getShape() met hod s.draw();
}
}
Output:
drawing circle
Abstract class having constructor, data member, methods
An abstract class can have data member, abstract method, method body, constructor and
even main() method.
Example2:
File: TestAbstraction2.java
//example of abstract class that have method body abstract class Bike{
Bike(){System.out.println("bike is created");} abstract void run(); void
changeGear(){System.out.println("gear changed");}
}
class Honda extends Bike{
void run(){System.out.println("running safely..");}
}
class TestAbstraction2{
public static void main(String args[]){ Bike obj = new Honda(); obj.run();
obj.changeGear();
}
}
Output:
bike is created running safely.. gear changed
The abstract class can also be used to provide some implementation of the interface. In
such case, the end user may not be forced to override all the methods of the interface.
Example3:
interface A{ void a();
void b(); void c();
void d();
}
abstract class B implements A{
public void c(){System.out.println("I am c");}
}
class M extends B{
public void a(){System.out.println("I am a");} public void b(){System.out.println("I am
b");} public void d(){System.out.println("I am d");}
}
class Test5{
public static void main(String args[]){ A a=new M(); a.a();
a.b();
a.c();
a.d(); }}
Output:
I am a I am b I am c I am d
Final keyword can be used along with variables, methods and classes.
1) final variable
2) final method
3) final class
1. Java final variable
A final variable is a variable whose value cannot be changed at anytime once assigned, it
remains as a constant forever.
Example:
public class Travel
{
final int SPEED=60; void
increaseSpeed(){
SPEED=70;
}
public static void main(String args[])
{
Travel t=new Travel(); t.increaseSpeed();
}
}
Output :
Exception in thread "main" java.lang.Error: Unresolved compilation problem: The
final field Travel.SPEED cannot be assigned
The above code will give you Compile time error, as we are trying to change the value of
a final variable ‘SPEED’.
class Parent
{
public final void disp()
{
System.out.println("disp() method of parent class");
}
}
public class Child extends Parent
{
public void disp()
{
System.out.println("disp() method of child class");
}
public static void main(String args[])
{
Child c = new Child(); c.disp();
}
}
Output : We will get the below error as we are overriding the disp() method of the Parent
class. Exception in thread "main" java.lang.VerifyError: class
com.javainterviewpoint.Child overrides final method disp.() at
java.lang.ClassLoader.defineClass1(Native Method) at
java.lang.ClassLoader.defineClass(Unknown Source)
at java.security.SecureClassLoader.defineClass(Unknown Source) at
java.net.URLClassLoader.defineClass(Unknown Source) at
java.net.URLClassLoader.access$100(Unknown Source) at
java.net.URLClassLoader$1.run(Unknown Source) at
java.net.URLClassLoader$1.run(Unknown Source)
3. Java final class
A final class cannot be extended(cannot be subclassed), lets take a look into the below
example package com.javainterviewpoint;
2. What are the differences between classes and interfaces ? (NOV/DEC 2020)
5. Outline how interfaces are implemented in java with an example? (NOV/DEC 2021)
Defining a Package
To create a package include a package command as the first statement in a Java source
file. Any classes declared within that file will belong to the specified package. The
package statement defines a name space in which classes are stored. If package
statement is omitted, the class names are put into the default package, which has no
name. Syntax: package <fully qualified package name>;
package pkg;
Here, pkg is the name of the package. For example, the following statement creates a
package called MyPackage.
package MyPackage;
Java uses file system directories to store packages. For example, the .class files for any
classes you declare to be part of MyPackage must be stored in a directory called
MyPackage.
A package hierarchy must be reflected in the file system of your Java development
system. For example, a package declared as package java.awt.image; needs to be
stored in java\awt\image in a Windows environment. We cannot rename a package
without renaming the directory in which the classes are stored.
When the second two options are used, the class path must not include MyPack,
itself. It must simply specify the path to MyPack. For example, in a Windows
environment, if the path to MyPack is C:\MyPrograms\Java\MyPack then the class path
to MyPack is C:\MyPrograms\Java
Example:
// A simple package package MyPack; class Balance { String name; double bal;
Balance(String n, double b) { name = n; bal
= b;
}
void show() { if(bal<0)
System.out.print("--> "); System.out.println(name + ": $" + bal);
}
}
class AccountBalance {
public static void main(String args[]) { Balance current[] = new Balance[3];
current[0] = new Balance("K. J. Fielding", 123.23); current[1] = new Balance("Will Tell",
157.02); current[2] = new Balance("Tom Jackson", -12.33); for(int i=0; i<3; i++)
current[i].show();
}
}
Call this file AccountBalance.java and put it in a directory called MyPack. Next,
compile the file. Make sure that the resulting .class file is also in the MyPack directory.
Then, try executing the AccountBalance class, using the following command line:
java MyPack.AccountBalance
Remember, you will need to be in the directory above MyPack when you execute this
command. (Alternatively, you can use one of the other two options described in the
preceding section to specify the path MyPack.)
As explained, AccountBalance is now part of the package MyPack. This means that it
cannot be executed by itself. That is, you cannot use this command line:
java AccountBalance
AccountBalance must be qualified with its package name.
The above syntax will create the package given in the sourceFile at the <target location of
pacakge> if it is not yet created. If package already exist then only the .class (byte code
file) will be stored to the package given in sourceFile.
Compile the code with the command on the command prompt. javac -d
DemoPackage.java
1. The command will create the package at the current location with the name pck1,
and contains the file DemoPackage.class and Student.class
2. To run write the command given below java pckl.DemoPackage
Note: The DemoPackate.class is now stored in pck1 package. So that we've to use fully
qualified type name to run or access it.
Output:
Roll No :: 1001
Name :: Alice
Address :: New York
Roll No :: 1002
Name :: Bob
Address :: Washington
3.1Interfaces
Syntax: interface
<interface_name>
{
Interface inheritance
A class implements interface but one interface extends another interface . Example:
interface Printable{ void print();
}
interface Showable extends Printable{ void show();
}
class TestInterface4 implements Showable{ public void print()
{System.out.println("Hello");}
public void show(){System.out.println("Welcome");} public static void main(String
args[]){ TestInterface4 obj = new TestInterface4(); obj.print(); obj.show();
}}
Output:
Hello Welcome
Nested Interface in Java
An interface can have another interface i.e. known as nested interface. interface
printable{ void print();
interface MessagePrintable{ void msg();
}
}
• Without bothering about the implementation part, we can achieve the security of
implementation
• In java, multiple inheritance is not allowed, however you can use interface to make
use