CS8392 Unit II Notes
CS8392 Unit II Notes
Unit II
INHERITANCE AND INTERFACES
Inheritance – Definition:
Keywords used:
o extends - In case of Java class and abstract class
o implements – In case of Java interface.
Syntax:
The extends keyword indicates that you are making a new class
that derives from an existing class.
Example of inheritance:
Field: Legs {
int legs;
...
}
Dog
Dog class Dog extends Animal
Field: Tail {
Super class : Animal
Sub class : Dog int tail;
Super class (Animal) has
...
datamember named legs
and subclass (Dog) has }
field named tail.
Filename : Dog.java
class Animal Output:
Dog has 4 legs
{ Dog has 1 tail
int legs = 4;
}
Types of Inheritance
Based on Based on
Java class interface
Single Inheritance:
When a subclass is derived from a single super class, is called as Single
Inheritance.
Subclass : student
Member function : display()
Filename : student.java
class person
{
String name = "Gayathri";
void detail() Super class
{
System.out.println("Am studying Java");
}
}
Multilevel Inheritance:
When a class extends a class, which in turn extends another class then it’s
called as multilevel inheritance. For example class C extends class B and class B
extends class A then this type of inheritance is known as multilevel inheritance.
Subclass : Employee
Data members : eno;
Subclass : Leader
Data members : teamsize;
class People
{ String name = "Gayathri";
void detail()
{
System.out.println("Method in Superclass");
}}
Hierarchical Inheritance
When multiple classes inherit from a single superclass, then this type of
inheritance is called as Hierarchical Inheritance. Here, there is one super class
and multiple sub classes.
Engineer
class Engineer
Output:
{ String college = "IIT"; } EEE student is studying in : IIT
CSE student is studying in : IIT
Civil student is studying in : IIT
class EEE extends Engineer { }
class CSE extends Engineer { }
Consider a scenario where A, B and C are three classes. The C class inherits A and B
classes. If A and B classes have same method and you call it from child class object,
there will be ambiguity to call method of A or B class.
Class A Class B
msg() msg()
Class C
Class C object, doesn’t know which msg() method to be invoked.
Filename : C.java
class A
{
void msg()
{
System.out.println("Hello");
}}
class B
{ void msg()
{
System.out.println("Welcome");
}}
Purpose of Inheritance
It promotes the code reusability i.e the same methods and variables which are
defined in a parent/super/base class can be used in the child/sub/derived class.
It promotes polymorphism by allowing method overriding.
Constructors in Java Inheritance:
In Java, super class default constructor is invoked automatically in sub class.
Object is created for the sub class. With the sub class object, super class constructors
are invoked.
Constructors in Multilevel Inheritance
Filename : Test.java
Class A is the Super class. Class B is inherited from Class A
class A class B extends A
{ {
A() B()
{ {
System.out.println("Class A "); System.out.println("Class B ");
} }
} }
Class C is inherited from Class B. Class D is inherited from Class C.
class C extends B class D extends C
{ {
C() D()
{ {
System.out.println("Class C "); System.out.println("Class D ");
}
}
}
}
public class Test
Output:
{
Class A
public static void main(String[] args) Class B
{ Class C
D d = new D(); Class D
}
Super Keyword in Java
The super keyword in java is a reference variable that is used to refer parent class
objects. The keyword “super” came into the picture with the concept of Inheritance. It is
majorly used in the following contexts:
Use of super with variables
Use of super with methods
Use of super with constructors
Sub class: B
class A Data members : number;
{ Member function : display()
{
System.out.println(number);
System.out.println(super.number);
}
}
Filename : Test.java
Super class: A
Member function : display()
class A
{
void display() Sub class: B
Member function : display()
{
System.out.println("This is Super class");
}
Filename : Test.java
Super class: A
Data members : num;
class A
Constructor : A()
{
int num;
Sub class: B
A() Constructor : B()
{
System.out.println("A is created");
}}
class B extends A
{ Super class default
constructor is invoked first
B()
{
System.out.println("B is created");
}}
{ System.out.println("A is created");
} Sub class: B
Constructor : B()
A(int num) B(num)
{
System.out.println("Number inside super class");
}}
Though one argument constructor
in the super class is available, only
class B extends A super class default constructor is
{ invoked.
B()
{ System.out.println("B is created"); }
B(int num)
{
System.out.println("Number inside sub lass");
}}
class B extends A
{
B()
{
System.out.println("B is created");
}
B(int num) One argument constructor in
the super class is invoked.
{
super(num);
System.out.println("Number inside sub class");
}}
} }
Polymorphism in Java
Polymorphism is derived from two Greek words: poly and morphs. The word
“poly” means many and “morphs” means forms. The ability to take more than one forms
is called as polymorphism.
{
System.out.println("Addition : "+ (n1+n2));
}
} }
When a method in a subclass has the same name, as a method in its super-class,
then it is said to override the method in the super-class.
Filename : Test.java
class Animal
{
void move()
{ System.out.println("Super class move"); }
} Output:
Super class move
sub class move
sub class move
class Dog extends Animal
{
void move()
{ System.out.println("sub class move"); }
}
Abstraction in Java
Abstraction is a process of hiding the implementation details and showing only
functionality to the user. There are two ways to achieve abstraction in java
Abstract class (0 to 100%)
Interface (100%)
Abstract class in Java
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). An abstract class is
never instantiated.
𝑎𝑏𝑠𝑡𝑟𝑎𝑐𝑡 𝑐𝑙𝑎𝑠𝑠 𝑐𝑙𝑎𝑠𝑠𝑛𝑎𝑚𝑒
{ 𝑀𝑒𝑚𝑏𝑒𝑟𝑠;
𝑐𝑜𝑛𝑐𝑟𝑒𝑡𝑒 𝑚𝑒𝑡ℎ𝑜𝑑𝑠;
𝐴𝑏𝑠𝑡𝑟𝑎𝑐𝑡 𝑚𝑒𝑡ℎ𝑜𝑑𝑠
Syntax :}
{ ;
ℎ ;
ℎ }
void display()
{
System.out.println("Hello CSE"); Concrete method
}
}
Abstract class are never instantiated which means we can't create an object to
Abstract class.
abstract class Test
{
void display()
{ System.out.println("Java Programming"); }
}
public class Normal extends Test
{
public static void main(String args[])
{ Compile time error
Test n= new Test(); Object for the abstract
class cannot be created
Filename : Test.java
abstract class Test Super class is the abstract class
{
Member function is declared, but NOT
abstract void msg();
DEFINED. This is Abstract method
void display()
Member function is
{ System.out.println("Java Programming");
defined. This is Concrete
} method.
}
Final variable
Final variables are nothing but constants. The value of a final variable cannot be
changed once it is initialized.
If final variables are not initialized with their values, it can be initialized only in the
constructors. It cannot be initialized with the member functions.
Final variables cannot be initialized inside methods.
public class race
{
final int speed ;
void run()
{ Compile time error
speed = 700; cannot assign a value to final variable speed
race()
{ Inside the constructor,
speed = 1000; final variables CAN
System.out.println("My speed is "+ speed); BE initialized
}
Final Methods
Final method cannot be overridden. Parent class final method can be used, but it
can’t be overridden in subclass.
Base class Derived class Description
class race public class Test extends race
{ { Super class has method,
void run() void run() run() and the sub class
{ { …. } also has the method,
… run().
} public static void main(String args[])
} { Super class, run() will
race r = new race(); be invoked
r.run();
} }
Base class Derived class Description
class race public class Test extends race
{ { Super class has method,
final void run() void run() run() and the sub class
{ { …. } also has the same
… method, run().
} public static void main(String args[])
} { Here, final methods
race r = new race(); CANNOT be overridden
r.run();
} } Note:
Final methods can be
inherited, but cannot be
overridden.
Final class
INTERFACES
Interface is a pure abstract class. They are syntactically similar to classes, but
objects cannot be created. Interface is used to achieve complete abstraction in
Java. It has the collection of
o Abstract methods
o Static and final constants.
Java uses interface to implement multiple inheritance.
Interface is written in a file with a .java extension, with the name of the
interface matching the name of the file.
Interface does not contain any constructors.
Interface is not extended by a class; it is implemented by a class and it can
extend multiple interfaces.
𝒊𝒏𝒕𝒆𝒓𝒇𝒂𝒄𝒆 𝑖𝑛𝑡𝑒𝑟𝑓𝑎𝑐𝑒𝑛𝑎𝑚𝑒
{
// 𝐴𝑛𝑦 𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑓𝑖𝑛𝑎𝑙,𝑠𝑡𝑎𝑡𝑖𝑐 𝑓𝑖𝑒𝑙𝑑𝑠
// 𝐴𝑛𝑦 𝑛𝑢𝑚𝑏𝑒𝑟 𝑜𝑓 𝑎𝑏𝑠𝑡𝑟𝑎𝑐𝑡 𝑚𝑒𝑡ℎ𝑜𝑑 𝑑𝑒𝑐𝑙𝑎𝑟𝑎𝑡𝑖𝑜𝑛𝑠
}
𝑃𝑢𝑏𝑙𝑖𝑐 𝑐𝑙𝑎𝑠𝑠 𝑐𝑙𝑎𝑠𝑠𝑛𝑎𝑚𝑒 𝑖𝑚𝑝𝑙𝑒𝑚𝑒𝑛𝑡𝑠 𝑖𝑛𝑡𝑒𝑟𝑓𝑎𝑐𝑒𝑛𝑎𝑚𝑒
{ }
Simple example to explain abstract class and abstract method in Java:
Filename : Test.java
interface Bank
{
Bank Interface int
double ROI = 14.5;
period = 4;
}
ℎ ,
{ { { {
… … … ℎ = ℎ ();
} } } }
Simple example:
Filename : Test.java
interface Father
{
int dad_amount = 500000; First interface - Father
}
interface Mother
{ Second interface - Mother
int mom_amount = 300000;
}
Filename : Test.java
interface Father
{
int amount = 500000;
} Same variable name in both
interfaces, Father and Mother
interface Mother
{
int amount = 300000;
}
Syntax
{
ℎ ;
Access Data members in the class can Data members in the interface
specifier be private, public or protected. are always public.
Members of the interface are
Members of the class need to
Members always constants. Either static
be always constants.
or final.
Methods inside the class are Methods in the interface are
Methods defined to perform a specific purely abstract. They are not
action. defined.
Representati
on
Difference between abstract class and interface
Abstract class and interface both are used to achieve abstraction where we can
declare the abstract methods. Abstract class and interface both can't be instantiated.
Representation
Syntax
;
ℎ ;
ℎ ;
Filename : Test.java
interface i2 extends i1
Since interface i1 extends i1, both i1 methods
{
and i2 methods are accessible via i2
public void f2();
}
void f3()
{
Method f3() definition of class cla
System.out.println("Class");
}
}
obj.f1();
obj.f2();
Output:
Interface1
cla c = new cla();
Interface2
c.f3();
Class
}
Object Cloning in Java
Already in Java copy constructor, we have seen the ways to copy the values of
one object into another in java. They are:
• By constructor
• By assigning the values of one object into another
• By clone() method of Object class
Types of cloning:
Java supports two type of cloning.
Deep cloning
Shallow cloning.
By default shallow clone is used in Java. Object class has a method clone() which does
shallow cloning.
Shallow copy is method of copying an object and is followed by default in cloning. In this
method the fields of an old object X are copied to the new object Y. While copying,
object Y will point to same location as pointed out by X.
If the field value is a primitive data type it copies the value of the primitive type.
Therefore, any changes made in referenced objects in object X or Y will be reflected in
other object.
Deep copy is to create a copy of object X and place it in a new object Y. New copies of
referenced objects fields are created and these references are placed in object Y. This
means any changes made in referenced object fields in object X or Y will be reflected
only in that object and not in the other. A deep copy copies all fields, and makes copies
of dynamically allocated memory pointed to by the fields.
s1.rollno = 1401;
System.out.println("s1 object rollno after updation: " + s1.rollno);
System.out.println("s2 object rollno after updation: " + s1.rollno);
}
catch(CloneNotSupportedException c){}
}
}
34 | U n i t I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
35 | U n i t I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Advantages of clone method:
If we use assignment operator to assign an object reference to another reference
variable then it will point to same address location of the old object and no new
copy of the object will be created. Due to this any changes in reference variable
will be reflected in original object.
If we use copy constructor, then we have to copy all of the data over explicitly i.e.
we have to reassign all the fields of the class in constructor explicitly. But in clone
method this work of creating a new copy is done by the method itself. So extra
processing is avoided in object cloning.
𝒄𝒍𝒂𝒔𝒔 𝑶𝒖𝒕𝒆𝒓
{
//𝑐𝑙𝑎𝑠𝑠 𝑂𝑢𝑡𝑒𝑟 𝑚𝑒𝑚𝑏𝑒𝑟𝑠
𝒄𝒍𝒂𝒔𝒔 𝑰𝒏𝒏𝒆𝒓
{
//𝑐𝑙𝑎𝑠𝑠 𝐼𝑛𝑛𝑒𝑟 𝑚𝑒𝑚𝑏𝑒𝑟𝑠
}
}
//𝑐𝑙𝑜𝑠𝑖𝑛𝑔 𝑜𝑓 𝑐𝑙𝑎𝑠𝑠 𝑂𝑢𝑡𝑒𝑟
There are two types of nested classes: non-static and static nested classes. The non-
static nested classes are also known as inner classes.
36 | U n i t I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Type Description
Inner class:
A Nested inner class can access any private instance variable in java which
can be of any outer class. We can also define the access of this Java inner class, i.e.
private, public or protected.
Syntax:
=
In this example, we are creating msg() method in member inner class that is
accessing the private data member of outer class.
Filename : Outer.java
Output:
public class Outer Data is 100
{
private int data = 100;
public class Inner
Inner Class
{
void msg(){System.out.println("Data is "+data);}
}
public static void main(String args[])
{
Outer obj = new Outer();
Inner Class
Outer.Inner in = obj.new Inner(); object is
in.msg(); created
}
}
Note:
Outer.Inner in = new Outer().new Inner(); can also be used.
37 | U n i t I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Method Local Inner class
A Method local inner class is a Java inner
class defined within a method of
an outer class in java. In Java, we can write a class
within a method and this will be a
local type. Like local variables, the scope of the inner
class is restricted within the
method.
Syntax:
𝑐𝑙𝑎𝑠𝑠 𝑜𝑢𝑡𝑒𝑟
{
𝑣𝑜𝑖𝑑 𝑚𝑒𝑡ℎ𝑜𝑑()
{ ……..
𝑐𝑙𝑎𝑠𝑠 𝑖𝑛𝑛𝑒𝑟
{}
}
}
Filename : Student.java
class Outer
{
int count;
public void display() Method display()
{
for(int i=0;i<5;i++)
{
class Inner
{
Inside method
public void show() there is a class ,
{ Inner
System.out.println("Inside inner "+(count++));
}
}
Inner in=new Inner();
in.show();
}
}
}
File: Test.java
class Demo
{
void show()
{
System.out.println("i am in show method of super class");
}
}
d.show(); Output:
} i am in show method of super class
} i am in anonymous inner class
39 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Java anonymous inner class example using interface
File: Demo.java
public class Demo
{
public static void main(String[] args)
{
h.show();
}
}
interface Hello
Output:
{
i am in anonymous class
void show();
}
Syntax
𝑐𝑙𝑎𝑠𝑠 𝑂𝑢𝑡𝑒𝑟 {
𝑠𝑡𝑎𝑡𝑖𝑐 𝑐𝑙𝑎𝑠𝑠 𝐼𝑛𝑛𝑒𝑟
{ }
}
}
}
40 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Java static nested class example
File: Outer.java
out.display();
obj.msg();
}
Output:
Given String is APEC
Given data : 100
41 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Advantage of java inner classes
There are basically three advantages of inner classes in java. They are:
Nested classes represent a special type of relationship that is it can access all
the members (data members and methods) of outer class including private.
Nested classes are used to develop more readable and maintainable code
because it logically group classes and interfaces in one place only.
Code Optimization: It requires less code to write.
Array Lists are like Rubber bands Arrays are like ropes. They are fixed.
42 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
ArrayList(Collection c): This constructor is used to build an array list
initialized with the elements from collection c
ArrayList(int capacity): This constructor is used to build an array list with
initial capacity being specified.
Methods in Java ArrayList:
Method Description
get(int index) Returns the element of a specified position within the list.
addAll(int index,
Insert all of the elements starting at the specified position
Collection C) from a specific collection into the mentioned list.
43 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Syntax:
44 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Syntax: Syntax: ArrayList.clone()
ArrayList.lastIindexOf(Object o)
45 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Syntax: ArrayList. remove(index) Syntax: ArrayList.toArray(T[] a)
46 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Filename : Test.java
import java.util.*;
public class Test {
Create an empty
public static void main(String[] args) {
array list, color_list
color_list.add("White");
Use add() method to
System.out.println("Given List:");
Print out the colors
for (int i = 0; i < 3; i++) in the ArrayList
System.out.println(color_list.get(i));
Append Green color
color_list.add(1,"Green"); at 2nd position
System.out.println("Green color is inserted:");
for (int i = 0; i < 4; i++)
System.out.println(color_list.get(i));
Index of the Black color
int i = color_list.indexOf("Black"); is determined
System.out.println("Black color is at
position :" +(i+1));
Black color is removed from the list
color_list.remove("Black");
}
}
Output:
Given List:
White
Black
Red
Green color is inserted:
White
Green
Black
Red
Black color is at position :3
After removing Black from the list
White
Green
Red
Combining color_list and animal_list
White
Green
Red
Lion
Tiger
Dog
Array is printed
White
Green
Red
Lion
Tiger
Dog
null
null
null
null
Java Strings
String is a sequence of characters. In Java programming language, strings are treated as objects.
The 𝒋𝒂𝒗𝒂.𝒍𝒂𝒏𝒈.𝑺𝒕𝒓𝒊𝒏𝒈 class is used to create string object. There are two ways to create a String object:
Implicit construction using string literal : Java String literal is created by using
double quotes.
o Example:= 𝑺𝒕𝒓𝒊𝒏𝒈 𝒔 = “𝑾𝒆𝒍𝒄𝒐𝒎𝒆”;
Explicit construction using new keyword : Java String is created by using a
keyword “new”.
o Example:= 𝑺𝒕𝒓𝒊𝒏𝒈 𝒔 = 𝒏𝒆𝒘 𝑺𝒕𝒓𝒊𝒏𝒈(“𝑾𝒆𝒍𝒄𝒐𝒎𝒆”);
Difference between string literal and new operator:
Java has provided a special mechanism for keeping the String literals - in a so-
called string common pool. If two string literals have the same contents, they will
share the same storage inside the common pool. This approach is adopted to
conserve storage for frequently-used strings. On the other hand, String objects
created via the new operator and constructor are kept in the heap. Each String object
in the heap has its own storage just like any other object. There is no sharing of
storage in heap even if two String objects have the same contents.
Defining and initializing Strings:
Simple example
String s1 = "Welcome to Java!";
String s2 = new String("Welcome to Java!"); //same as s1
Numbers as strings
String s3 =“12345”;
String s4 = new String(s3); //s4 will hold same value as s3
Char array as strings
char[] helloArray = { 'h', 'e', 'l', 'l', 'o', '.'
}; String s5= new String(helloArray);
49 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Simple Example for Defining and initializing Strings
Filename : Test.java
public class Test
{ public static void main(String args[])
{
String s1 = "Welcome to Java!";
Creating string by
System.out.println("Using String Literal : " + s1); java string literal
Java String class implements three interfaces, namely – Serializable, Comparable and
CharSequence. The CharSequence interface is used to represent sequence of
characters. It is implemented by String, StringBuffer and StringBuilder classes. It
means, we can create string in java by using these 3 classes.
50 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
In Java, Strings are immutable. By immutable means, Strings are constant;
their values cannot be changed after they are created. For mutable string, you can
use StringBuffer and StringBuilder classes.
Converts all the characters of the String to lower String s1="H R You?”;
toLowerCase()
case. s1.toLowerCase() = h r you?
Converts all the characters of the String to upper String s1="H R You?”;
toUpper()
case. s1.toUpperCase() = H R YOU?
int value=20;
String s1;
ValueOf() Converts different types of values into string.
s1=String.valueOf(value);
s1+18 = 2018
51 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Method Description Example
String s1 =" hello hai hi!";
Searches the sequence of characters in the s1.contains("hi") = true
contains()
string. If found, return true else return false s1.contains("helloo") = false
s1.contains("hru") = false
Filename : Test.java
Import the utility arrays to use
import the sort function in the program
java.util.Arrays; public
class Test {
public static void main(String[] args)
{
String str = "javaprogramming";
Given string is converted to
char a[] = str.toCharArray(); character array and then it is sorted
Output:
Input String : javaprogramming
Sorted String : aaaggijmmnoprrv
52 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s
Java program to sort the numbers in alphabetical order:
Filename : Test.java
Output:
import java.util.Arrays; Input Array Elements: 100 67 89 32 65 75
Sorted Array : 32 65 67 75 89 100
Arrays.sort(num);
Sorting the Integer array
System.out.println();
System.out.print("Sorted Array : " );
for (int i = 0; i < num.length; i++)
System.out.print(num[i] + " ");
} }
System.out.println();
System.out.print("Sorted strings
: " );
for (int i = 0; i < str.length; i++) Output:
System.out.print(str[i] + " "); Input Strings: thankyou hai every babuji god
Sorted strings : babuji every god hai thankyou
}
}
53 | U n i t I I – O b j e c t O r i e n t e d P r o g r a m m i n g n o t e s