OOP Unit-2
OOP Unit-2
PROGRAMMING
(BMC-202)
Presented by -
Page 1
Terms used in Inheritence
Class: A class is a group of objects which have common
properties. It is a template or blueprint from which objects
are created.
Sub Class/Child Class: Subclass is a class which inherits the
other class. It is also called a derived class, extended class, or
child class.
Super Class/Parent Class: Superclass is the class from
where a subclass inherits the features. It is also called a base
class or a parent class.
Reusability: As the name specifies, reusability is a
mechanism which facilitates you to reuse the fields and
methods of the existing class when you create a new class.
You can use the same fields and methods already defined in
previous class.
SINGLE INHERITANCE
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
In Hierarchical Inheritance, one class is inherited by many sub classes.
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();
//Assigning ClassD object to ClassD reference
ClassD d = new ClassD();
//call dispD() method of ClassD
d.dispD();
//call dispA() method of ClassA
d.dispA();
}
}
Output :
disp() method of ClassB
disp() method of ClassA
disp() method of ClassC
disp() method of ClassA
disp() method of ClassD
disp() method of ClassA
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 one class. Multiple
Inheritance is basically not supported by many Object Oriented Programming languages such as
Java, Small Talk, C# etc.. (C++ Supports Multiple 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.
“super” KEYWORD
Usage of super keyword
1.super() invokes the constructor of the parent class.
2.super.variable_name refers to the variable in the parent class.
3.super.method_name refers to the method of the parent class.
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[]){
//Calling default constructor
SubClass s = new SubClass();
//Calling parameterized constructor
SubClass s1 = new SubClass(10);
}
}
Output
Parent Class default Constructor called
Child Class default Constructor called
Parent Class parameterized Constructor, value: 10
Child Class parameterized Constructor, value: 10
2. super.variable_name refers to the variable in the parent class
When we have the same variable in both parent and subclass
class ParentClass{
int val=999;
}
public class SubClass extends ParentClass{
int val=123;
void disp()
{
System.out.println("Value is : "+val);
}
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);
}
Output
Value is : 999
3. super.method_nae refers to the method of the parent class
When you override the Parent Class method in the Child Class without super keywords support you will
not be able to call the Parent Class method. Let’s look into the below example
class ParentClass
{
void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
void disp()
{
System.out.println("Child Class method");
}
void show()
{
disp();
}
public static void main(String args[])
{
SubClass s = new SubClass(); s.show();
}
}
Output:
Child Class method
Here we have overridden the Parent Class disp() method in the SubClass and hence SubClass disp() method is called. If
we want to call the Parent Class disp() method also means then we have to use the super keyword for it.
class ParentClass
{
void disp()
{
System.out.println("Parent Class method");
}
}
public class SubClass extends ParentClass
{
void disp()
{
System.out.println("Child Class method");
}
void show()
{
//Calling SubClass disp() method
disp();
//Calling ParentClass disp() method
super.disp();
}
public static void main(String args[])
{
SubClass s = new SubClass();
s.show();
}
}
Output
Child Class method
Parent Class method
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
The Object Class
There is one special class, Object, defined by Java. All other classes are subclasses of
Object. That is, Object is a superclass of all other classes. This means that a reference
variable of type Object can refer to an object of any other class. Also, since arrays are
implemented as
classes, a variable of type Object can also refer to any array. Object defines the
following methods, which means that they are available in every object.
The methods getClass( ), notify( ), notifyAll( ), and wait( ) are declared as final. You
may override the others. These methods are described elsewhere in this book. However,
notice two methods now: equals( ) and toString( ).
The equals( ) method compares two objects. It returns true if the objects are equal, and
false otherwise. The precise definition of equality can vary, depending on the type of
objects being compared.
The toString( ) method returns a string that contains a description of the object on
which it is called. Also, this method is automatically called when an object is output using
println( ). Many classes override this method. Doing so allows them to tailor a
description specifically for the types of objects that they create.
ABSTRACT CLASS
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.
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
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");
Output:
} I am a
public void b(){ I am b
System.out.println("I am b"); I am c
}
I am d
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();
}}
INTERFACE IN JAVA
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 and multiple
inheritance.
Interface is declared by using interface keyword. It provides total abstraction;
means all the methods in interface are declared with empty body and are public and
all fields are public, static and final by default. A class that implement interface must
implement all the methods declared in the interface.
Syntax:
interface <interface_name>
{
Page 14
Relationship between classes and interfaces
Example:
interface printable{
void print();
}
class A6 implements printable{
public void print(){
System.out.println("Hello");
}
public static void main(String args[]){
A6 obj = new A6();
obj.print();
}
}
Output:
Hello
Example: interface Drawable
{
void draw();
}
class Rectangle implements Drawable{
public void draw(){
System.out.println("drawing rectangle");
}}
class Circle implements Drawable{
public void draw(){System.out.println("drawing circle");}
}
class TestInterface1{
public static void main(String args[]){
Drawable d=new Circle();//In real scenario, object is provided by method e.g. getDrawable()
d.draw();
}
}
Output:
drawing circle
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces i.e. known
as multiple inheritance.
Example:
interface Printable{
void print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){
System.out.println("Hello");
}
public void show(){
System.out.println("Welcome");
}
public static void main(String args[]){
A7 obj = new A7();
obj.print();
obj.show();
}}
Output:
Hello
Welcome
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();
}
}
Key points to remember about interfaces:
1)We can’t instantiate an interface in java. That means we cannot create the object
of an interface
2)Interface provides full abstraction as none of its methods have body. On the
other hand abstract class provides partial abstraction as it can have abstract
and concrete(methods with body) methods both.
3)“implements” keyword is used by classes to implement an interface.
4)While providing implementation in class of any method of an interface, it
needs to be mentioned as public.
5)Class that implements any interface must implement all the methods of that
interface, else the class should be declared abstract.
6)Interface cannot be declared as private, protected or transient.
7)All the interface methods are by default abstract and public.
8)Variables declared in interface are public, static and final by
default.
interface Try {
int a=10;
public int a=10;
public static final int a=10;
final int a=10;
static int a=0;
}
All of the above statements are identical.
Key points to remember about interfaces:
9) Interface variables must be initialized at the time of declaration otherwise compiler will throw an
error.
interface Try
{
int x;//Compile-time error
}
Above code will throw a compile time error as the value of the variable x is not initialized at the
time of declaration.
10)Inside any implementation class, you cannot change the variables declared in interface
because by default, they are public, static and final. Here we are implementing the interface
“Try” which has a variable x. When we tried to set the value for variable x we got compilation
error as the variable x is public static final by default and final variables can not be re-initialized.
11). An interface can extend any interface but cannot implement it. Class implements interface
and interface extends interface.
1 2 ) A class can implement any number of interfaces.
13)If there are two or more same methods in two interfaces and a class implements both
interfaces, implementation of the method once is enough.
interface A
{
public void aaa();
}
interface B
{
public void aaa();
}
class Central implements A,B
{
public void aaa()
{
//Any Code here
}
public static void main(String args[])
{
//Statements
}
}
1 4 ) A class cannot implement two interfaces that have methods with same name but different return type.
interface A {
public void aaa();
}
interface B {
public int aaa();
}
class Central implements A,B {
public void aaa() / / error
{
}
public int aaa() // error
{
}
public static void main(String args[]){
}
}
15) Variable names conflicts can be resolved by interface name.
interface A {
int x=10;
}
interface B {
int x=100;
}
class Hello implements A,B {
public static void Main(String args[]){
System.out.println(x);
System.out.println(A.x);
System.out.println(B.x);
}
}
Advantages of interface in java:
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 of it as you can implement more than one interface.
9)Example: Example:
public abstract class Shape{ public interface Drawable{
public abstract void draw(); void draw();
} }
FINAL KEYWORD
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’.
2. Java final method
When you declare a method as final, then it is called as final method. A final method cannot be
overridden.
package com.javaprogram;
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)
Java final class
A final class cannot be extended(cannot be subclassed), lets take a look into the
below example
package com.javaprogram;
Output :
We will get the compile time error like “The type Child cannot subclass the
final class Parent”
Exception in thread "main" java.lang.Error: Unresolved compilation problem
OBJECT CLONING
The object cloning is a way to create exact copy of an object. The clone() method of
Object class is used to clone an object.
The java.lang.Cloneable interface must be implemented by the class whose
object clone we want to create. If we don't implement Cloneable interface,
clone() method generates CloneNotSupportedException.
The clone() method is defined in the Object class.
Syntax of the clone() method:
protected Object clone() throws CloneNotSupportedException
The clone() method saves the extra processing task for creating the exact copy of an
object. If we perform it by using the new keyword, it will take a lot of processing time
to be performed that is why we use object cloning.
Advantage of Object cloning
You don't need to write lengthy and repetitive codes. Just use an abstract class
with a 4- or 5-line long clone() method.
It is the easiest and most efficient way for copying objects, especially if we are
applying it to an already developed or an old project. Just define a parent class,
implement Cloneable in it, provide the definition of the clone() method and the
task will be done.
Clone() is the fastest way to copy array.
Disadvantage of Object cloning
To use the Object.clone() method, we have to change a lot of syntaxes to our
code, like implementing a Cloneable interface, defining the clone() method
and handling CloneNotSupportedException, and finally, calling Object.clone()
etc.
We have to implement cloneable interface while it doesn?t have any methods in
it. We just have to use it to tell the JVM that we can perform clone() on our object.
Object.clone() is protected, so we have to provide our own clone() and
indirectly call Object.clone() from it.
Object.clone() doesn?t invoke any constructor so we don?t have any control
over object construction.
If you want to write a clone method in a child class then all of its superclasses
should define the clone() method in them or inherit it from another parent class.
Otherwise, the super.clone() chain will fail.
Object.clone() supports only shallow copying but we will need to override it if
we need deep cloning.
Example of clone() method (Object cloning)
class Student implements Cloneable{
int rollno;
String name;
Student(int rollno,String name){
this.rollno=rollno;
this.name=name;
}
public Object clone()throws CloneNotSupportedException{
return super.clone();
}
public static void main(String args[]){
try{
Student s1=new Student(101,"amit");
Student s2=(Student)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}
catch(CloneNotSupportedException c){}
}}
Output:
101 amit
101 amit
INNER CLASSES
Inner class means one class which is a member of another class. There are basically four
types of inner classes in java.
1)Nested Inner class
2)Method Local inner classes
3)Anonymous inner classes
4)Static nested classes
Nested Inner class
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
Method Local inner classes
Inner class can be declared within a method of an outer class. In the following example,
Inner is an inner class in outerMethod().
Example:
class Outer {
void outerMethod() {
System.out.println("inside outerMethod");
// Inner class is local to outerMethod()
class Inner {
void innerMethod() {
System.out.println("inside innerMethod");
}
}
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
Static nested classes
Static nested classes are not technically an inner class. They are like a static member of outer
class.
Example:
// Java program to demonstrate accessing a static nested class outer class
class OuterClass {
// static member
static int outer_x = 10;
// instance(non-static) member
int outer_y = 20;
// private member
private static int outer_private = 30;
// static nested class
static class StaticNestedClass {
void display() {
// can access static member of outer class
System.out.println("outer_x = " + outer_x);
// The following statement will give compilation error as static nested class cannot directly
// access non-static members
// System.out.println("outer_y = " + outer_y);
// Therefore create object of the outer class
// to access the non-static member
OuterClass out = new OuterClass();
System.out.println("outer_y = " + out.outer_y);
}
}
}
// Driver class
public class StaticNestedClassDemo {
public static void main(String[] args)
{
// accessing a static nested class
OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();
nestedObject.display();
}
}
Output:
outer_x = 10
outer_private = 30
outer_y = 20
Anonymous inner classes
Anonymous inner classes are declared without any name at all. They are created in two ways.
1. a superclass that an anonymous class extends
2. an interface that an anonymous class implements
METHOD DESCRIPTION
void add(int index, Object It is used to insert the specified element at the specified position index
element) in a list.
boolean addAll(Collection c) It is used to append all of the elements in the specified collection to
the end of this list, in the order that they are returned by the specified
collection's iterator.
void clear() It is used to remove all of the elements from this list.
int lastIndexOf(Object o) It is used to return the index in this list of the last occurrence of
the specified element, or -1 if the list does not contain this element.
Object[] toArray() It is used to return an array containing all of the elements in this list in
the correct order.
Object[] toArray(Object[] It is used to return an array containing all of the elements in this
a) list in the correct order.
boolean add(Object o) It is used to append the specified element to the end of a list.
boolean addAll(int index, It is used to insert all of the elements in the specified collection into
Collection c) this list, starting at the specified position.
Object clone() It is used to return a shallow copy of an ArrayList.
int indexOf(Object o) It is used to return the index in this list of the first occurrence of
the specified element, or -1 if the List does not contain this
element.
Java ArrayList Example: Book Example:
import java.util.*;
class Book {
int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int quantity) {
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
} }
public class ArrayListExample {
public static void main(String[] args) {
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list list.add(b1);
list.add(b2);
list.add(b3);
//Traversing list for(Book b:list){
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}} }
Output:
101Let us C Yashwant Kanetkar BPB 8
102Data Communications & Networking Forouzan Mc Graw Hill 4
103Operating System Galvin Wiley 6