UNIT 2 Notes
UNIT 2 Notes
UNIT 2 Notes
INHERITANCE
Inheritance can be defined as the procedure or mechanism of acquiring all the properties
and behaviors of one class to another, i.e., acquiring the properties and behavior of child class
from the parent class.
When one object acquires all the properties and behaviours of another object, it is known
as inheritance. Inheritance represents the IS-A relationship, also known as parent-child
relationship.
Uses of inheritance in java
For Method Overriding (so runtime polymorphism can be achieved).
For Code Reusability.
Types of inheritance in java: single, multilevel and hierarchical inheritance. Multiple and
hybrid inheritance is supported through interface only.
Syntax:
class subClass extends superClass
{
//methods and fields
}
Page 1
CS8392 /Object Oriented Programming
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
Page 2
CS8392 /Object Oriented Programming
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.
Page 3
CS8392 /Object Oriented Programming
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();
Page 4
CS8392 /Object Oriented Programming
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.
Page 5
CS8392 /Object Oriented Programming
{
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
Page 6
CS8392 /Object Oriented Programming
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
Page 7
CS8392 /Object Oriented Programming
int val=999;
}
public class SubClass extends ParentClass
{
int val=123;
void disp()
{
System.out.println("Value is : "+val);
}
void disp()
{
System.out.println("Value is : "+super.val);
}
Output
Value is : 999
Page 8
CS8392 /Object Oriented Programming
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
{
Page 9
CS8392 /Object Oriented Programming
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
Page 10
CS8392 /Object Oriented Programming
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.
Example abstract class:
abstract class A{}
abstract method:
Page 11
CS8392 /Object Oriented Programming
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..");}
}
Page 12
CS8392 /Object Oriented Programming
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
Page 13
CS8392 /Object Oriented Programming
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>
{
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
Page 14
CS8392 /Object Oriented Programming
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
Example: interface
Printable{ void
print();
}
interface Showable{
void show();
}
class A7 implements Printable,Showable{
public void print(){System.out.println("Hello");}
Page 15
CS8392 /Object Oriented Programming
obj.show();
}}
Output:
Hello
Welcome
Page 16
CS8392 /Object Oriented Programming
Page 17
CS8392 /Object Oriented Programming
Page 18
CS8392 /Object Oriented Programming
}
}
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);
}
}
Page 19
CS8392 /Object Oriented Programming
6) An abstract class can extend another Java An interface can extend another Java interface
class and implement multiple Java interfaces. only.
7) An abstract class can be extended using An interface class can be implemented using
keyword extends. keyword implements
8) A Java abstract class can have class members Members of a Java interface are public by
like private, protected, etc. default.
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
Page 20
CS8392 /Object Oriented Programming
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;
Page 21
CS8392 /Object Oriented Programming
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.
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.
Page 22
CS8392 /Object Oriented Programming
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
Page 23
CS8392 /Object Oriented Programming
Page 24
CS8392 /Object Oriented Programming
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
Page 25
CS8392 /Object Oriented Programming
STRINGS IN JAVA
In java, string is basically an object that represents sequence of char values. Java String provides
a lot of concepts that can be performed on a string such as compare, concat, equals, split, length,
replace, compareTo, intern, substring etc.
In java, string objects are immutable. Immutable simply means unmodifiable or unchangeable.
String s="javatpoint";
There are two ways to create String object:
1. By string literal
2. By new keyword
1 ) String Literal
Java String literal is created by using double quotes. For Example:
String s="welcome";
2) By new keyword
String s=new String("Welcome");
Page 26
CS8392 /Object Oriented Programming
String methods:
1. char charAt(int index) returns char value for the particular index
2. int length() returns string length
3. static String format(String format, returns formatted string
Object... args)
4. static String format(Locale l, String returns formatted string with given locale
format, Object... args)
5. String substring(int beginIndex) returns substring for given begin index
6. String substring(int beginIndex, int returns substring for given begin index and end
endIndex) index
7. boolean contains(CharSequence s) returns true or false after matching the sequence
of char value
8. static String join(CharSequence returns a joined string
delimiter, CharSequence... elements)
9. static String join(CharSequence returns a joined string
delimiter, Iterable<? extends
CharSequence> elements)
10. boolean equals(Object another) checks the equality of string with object
11. boolean isEmpty() checks if string is empty
12. String concat(String str) concatinates specified string
13. String replace(char old, char new) replaces all occurrences of specified char value
14. String replace(CharSequence old, replaces all occurrences of specified
CharSequence new) CharSequence
15. static String equalsIgnoreCase(String compares another string. It doesn't check case.
another)
16. String[] split(String regex) returns splitted string matching regex
17. String[] split(String regex, int limit) returns splitted string matching regex and limit
18. String intern() returns interned string
19. int indexOf(int ch) returns specified char value index
20. int indexOf(int ch, int fromIndex) returns specified char value index starting with
given index
21. int indexOf(String substring) returns specified substring index
22. int indexOf(String substring, int returns specified substring index starting with
fromIndex) given index
23. String toLowerCase() returns string in lowercase.
24. String toLowerCase(Locale l) returns string in lowercase using specified locale.
25. String toUpperCase() returns string in uppercase.
26. String toUpperCase(Locale l) returns string in uppercase using specified
locale.
27. String trim() removes beginning and ending spaces of this
string.
28. static String valueOf(int value) converts given type into string. It is overloaded.
Page 27
CS8392 /Object Oriented Programming
Example:
public classstringmethod
{
public static void main(String[] args)
{
String string1 = new String("hello");
String string2 = new String("hello");
if (string1 == string2)
{
System.out.println("string1= "+string1+" string2= "+string2+" are equal");
}
else
{
System.out.println("string1= "+string1+" string2= "+string2+" are Unequal");
}
System.out.println("string1 and string2 is=
"+string1.equals(string2)); String a="information";
System.out.println("Uppercase of String a is=
"+a.toUpperCase()); String b="technology";
System.out.println("Concatenation of object a and b is= "+a.concat(b));
System.out.println("After concatenation Object a is= "+a.toString());
System.out.println("\"Joseph\'s\" is the greatest\\ college in
chennai"); System.out.println("Length of Object a is= "+a.length());
System.out.println("The third character of Object a is= "+a.charAt(2));
StringBuffer n=new StringBuffer("Technology");
StringBuffer m=new StringBuffer("Information");
System.out.println("Reverse of Object n is= "+n.reverse());
n= new StringBuffer("Technology");
System.out.println("Concatenation of Object m and n is= "+m.append(n));
System.out.println("After concatenation of Object m is= "+m);
}
}
Output:
string1= hello string2= hello are Unequal
string1 and string2 is= true
Uppercase of String a is= INFORMATION
Concatenation of object a and b is= informationtechnology
After concatenation Object a is= information
"Joseph's" is the greatest\ college in chennai
Length of Object a is= 11
The third character of Object a is= f
Reverse of Object n is= ygolonhceT
Concatenation of Object m and n is= InformationTechnology
Page 28
CS8392 /Object Oriented Programming
Page 29
CS8392 /Object Oriented Programming