Unit 2 (Oops)
Unit 2 (Oops)
Inheritance – Super classes- sub classes –Protected members – constructors in sub classes-
the Object class – abstract classes and methods- final methods and classes – Interfaces –
defining an interface, implementing interface, differences between classes and interfaces
and extending interfaces - Object cloning -inner classes, Array Lists - Strings
Definition:
Inheritance can be defined as the process where one class acquires the properties
(methods and fields) of another. With the use of inheritance the information is made
manageable in a hierarchical order.
The class which inherits the properties of other is known as subclass (derived class,
child class) and the class whose properties are inherited is known as superclass (base class,
parent class).
Inheritance uses:
For Method Overriding (used for Runtime Polymorphism).
It's main uses are to enable polymorphism and to be able to reuse code for different
classes by putting it in a common super class
For code Re-usability
extends Keyword
extends is the keyword used to inherit the properties of a class. Following is the
syntax of extends keyword.
Syntax
class Super {
.....
.....
}
class Sub extends Super
{
.....
.....
}
Advantage of inheritance
Types of Inheritance
Single inheritance
Multilevel inheritance
Hierarchical inheritance
Multiple inheritance
Example
class Calculation {
int z;
Multilevel Inheritance
class Grand
{
public void m1()
{
System.out.println("Class Grand method");
}
}
class Parent extends Grand
{
public void m2()
{
System.out.println("Class Parent method");
}
}
class Child extends Parent
{
3
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
public void m3()
{
System.out.println("Class Child method");
}
public static void main(String args[])
{
Child obj = new Child();
obj.m1();
obj.m2();
obj.m3();
}
}
Output:
Class Grand method
Class Parent method
Class Child method
Hierarchical Inheritance
When one base class can be inherited by more than one class, then it is called
hierarchical inheritance.
class A
{
public void m1()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void m2()
4
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void m3()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void m4()
{
System.out.println("method of Class D");
}
}
public class MainClass
{
public void m5()
{
System.out.println("method of Class MainClass");
}
public static void main(String args[])
{
A obj1 = new A();
B obj2 = new B();
C obj3 = new C();
D obj4 = new D();
obj1.m1();
obj2.m1();
obj3.m1();
obj4.m1();
}
}
Output:
method of Class A
method of Class A
method of Class A
method of Class A
5
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Multiple Inheritances
In multiple inheritance, one derive class can extend more than one base class.
Multiple inheritances are basically not supported by Java, because it increases the
complexity of the code.
But they can be achieved by using interfaces.
class X
{
void display()
{
System.out.println("class X dispaly method ");
}
}
class Y
{
void display()
{
System.out.println("class Y display method ");
}
}
public class Z extends X,Y
{
public static void main(String args[])
{
Z obj=new Z();
obj.display();
}
}
Output:
Compile time error
6
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Why multiple inheritance is not supported in Java
To remove ambiguity.
To provide more maintainable and clear design.
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.
interface Inf1
{
public void method1();
}
interface Inf2 extends Inf1
{
public void method2();
}
public class Demo implements Inf2
{
Type 2:( super can be used to invoke immediate parent class method. )
class Parentclass
{
void display() //Overridden method
{
System.out.println("Parent class method");
}
}
class Subclass extends Parentclass
{
void display() //Overriding method
{
System.out.println("Child class method");
void printMsg()
{
display(); //This would call Overriding method
super.display(); //This would call Overridden method
}
public static void main(String args[])
{
Subclass obj= new Subclass();
obj.printMsg();
}
}
Output:
Child class method
Parent class method
class Parentclass
{
Parentclass()
{
System.out.println("Constructor of Superclass");
}
}
class Subclass extends Parentclass
{
Subclass()
{
System.out.println("Constructor of Subclass");
}
Subclass(int num)
{
System.out.println("Constructor with arg");
}
void display()
{
System.out.println("Hello");
}
public static void main(String args[]){
Subclass obj= new Subclass();
obj.display();
Subclass obj2= new Subclass(10);
obj2.display();
}
}
Output:
Constructor of Superclass
Constructor of Subclass
Hello
Constructor of Superclass
Constructor with arg
Hello
10
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Program2:
class Employee
{
Employee()
{
System.out.println("Employee class Constructor");
}
}
class HR extends Employee
{
HR( )
{
super( ); //will invoke or call parent class constructor
System.out.println("HR class Constructor");
}
}
class Supercons
{
public static void main(String[] args)
{
HR obj=new HR();
}
}
Output
Employee class Constructor
HR class Constructor
Abstract Method
If a method is declared as an abstract, then it is called abstract method.
It does not have implementation.
It contains method signature but not method body.
Syntax : abstract return_type function_name (); // No definition
11
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Program1:
abstract class A
{
abstract void callme(); // abstract method declared only
public void normal() // concrete method
{
System.out.println("this is concrete method");
}
}
class B extends A
{
void callme()
{
System.out.println("this is callme.");
}
public static void main(String[] args)
{
B b = new B();
b.callme();
b.normal();
}
}
Output: this is callme.
this is concrete method
Abstraction using abstract class
System.out.println("Car engine");
}
public static void main(String[] args)
{
Vehicle v = new Car();
v.engine();
}
} Output: Car engine
12
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Program 3:
Write a Java Program to create an abstract class named Shape that contains two integers and
an empty method named print Area(). Provide three classes named Rectangle, Triangle and
Circle such that each one of the classes extends the class Shape. Each one of the classes
INTERFACE
An interface is a reference type in Java. It is similar to class. It is a collection of abstract
methods. A class implements an interface, thereby inheriting the abstract methods of the
interface. Interface is a pure abstract class. Interface is used to achieve complete abstraction
in Java.
Syntax :
interface interface_name
{
-------
}
Example of Interface
interface Moveable
{
int AVERAGE-SPEED=40;
void move();
}
13
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
IMPLEMENTING INTERFACES
Syntax:
interface F1
{ ….. }
class C1 implements F1
{
………}
Example: /* File name : MammalInt.java */
interface Animal
{
void eat();
void travel()
int noOfLegs();
}
public class MammalInt implements Animal {
EXTENDING INTERFACES
An interface can extend another interface. The extends keyword is used to extend an
interface, and the child interface inherits the methods of the parent interface.The following
Sports interface is extended by Hockey and Football interfaces.
14
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Example: // Filename: Sports.java
public interface Sports {
public void setHomeTeam(String name);
public void setVisitingTeam(String name);
}
// Filename: Football.java
public interface Football extends Sports {
public void homeTeamScored(int points);
public void visitingTeamScored(int points);
public void endOfQuarter(int quarter);
}
// Filename: Hockey.java
public interface Hockey extends Sports {
public void homeGoalScored();
public void visitingGoalScored();
public void endOfPeriod(int period);
public void overtimePeriod(int ot);
}
Difference between an interface and an abstract class
15
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
FINAL KEYWORD IN JAVA
final keyword can be used along with variables, methods and classes.
1) final variable
2) final method
3) final class
1) final variable
final variables are nothing but constants. We cannot change the value of a final
variable once it is initialized. Lets have a look at the below code:
class Bike{
void run(){
speedlimit=400;
obj.run();
} } Output:Compile Time Error
class Bike{
{ System.out.println("running");
void run()
16
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
}
honda.run();
void run()
h1.run();
Ans) Yes, final method is inherited but you cannot override it. For Example:
17
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
class Bike{
System.out.println("running...");}
new Honda2().run();
Output:running...
18
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
NESTED CLASS
A class within another class is known as Nested class. The scope of the nested is
bounded by the scope of its enclosing class.
Static Nested Class
A static class i.e. created inside a class is called static nested class in java. It cannot access
non-static data members and methods. It can be accessed by outer class name.
It can access static data members of outer class including private.
Static nested class cannot access non-static (instance) data member or method.
class TestOuter
{
static int data=30;
static class Inner
{
void msg()
{
System.out.println("data is "+data);
}
}
public static void main(String args[])
{
TestOuter.Inner obj=new TestOuter.Inner();
obj.msg();
}
}
Output:30
Non-static Nested class is most important type of nested class. It is also known as
Inner class. It has access to all variables and methods of Outer class and may refer to them
directly. But the reverse is not true, that is, Outer class cannot directly access members of
Inner class.
One more important thing to notice about an Inner class is that it can be created only
within the scope of Outer class. Java compiler generates an error if any code outside Outer
class attempts to instantiate Inner class.
19
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Program:1
class Outer
{
class Inner
{
public void show()
{
System.out.println("Inside inner");
}
}
public void display()
{
Inner in=new Inner();
in.show();
}
}
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
Output : Inside inner
20
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Program:2
public class outer
{
private int data=30; //instance variable
void display()
{
class Local
{
void msg()
{
System.out.println(data);
}
}
Local obj=new Local();
obj.msg();
}
public static void main(String args[])
{
outer obj2=new outer();
obj2.display();
}
} Output : 30
2. Method Local Inner Class (method(){Inner class} )
class Outer
{
int count;
public void display()
{
for(int i=0;i<5;i++)
{
class Inner{ //Inner class defined inside for loop
public void show() {
System.out.println("Inside inner "+(count++));
}
}
Inner in=new Inner();
in.show();
}
}}
class Test
{
public static void main(String[] args)
{
Outer ot=new Outer();
ot.display();
}
}
21
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Output :
Inside inner 0
Inside inner 1
Inside inner 2
Inside inner 3
Inside inner 4
22
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
JAVA STRING
For example:
1. char[] ch={'j','a','v','a','t','p','o','i','n','t'};
2. String s=new String(ch);
is same as: String s="javatpoint";
The java.lang.String class implements Serializable and Comparable interfaces.
1. By string literal
2. By new keyword
1) String Literal
String s1="Welcome";
String s2="Hello";
2) By new keyword :
Example Program:
char ch[]={'s','t','r','i','n','g','s'};
System.out.println(s1);
System.out.println(s2);
System.out.println(s3);
}}
23
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Immutable String in Java
In java, string objects are immutable. Immutable simply means unmodifiable or
unchangeable.
class Testimmutablestring{
String s="Sachin";
} }
1. By equals() method
2. By = = operator
3. By compareTo() method
The String equals() method compares the original content of the string. It compares values
of string for equality. String class provides two methods:
public boolean equals(Object another) compares this string to the specified object.
public boolean equalsIgnoreCase(String another) compares this String to another
string, ignoring case.
class Teststringcomparison1{
String s4="Saurav";
System.out.println(s1.equals(s2));//true
System.out.println(s1.equals(s3));//true
System.out.println(s1.equals(s4));//false
}
24
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Using equals() method
String s = "Hell";
String s1 = "Hello";
String s2 = "Hello";
s1.equals(s2); //true
s.equals(s1) ; //false
class Teststringcomparison3{
String s1="Sachin";
String s2="Sachin";
} }
Using == operator
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2) //true
test(s1 == s3) //false
If:
s1 == s2 :0
s1 > s2 :positive value
s1 < s2 :negative value
Example program:
class Teststringcomparison4
{
public static void main(String args[]){
String s1="Sachin";
String s2="Sachin";
String s3="Ratan";
System.out.println(s1.compareTo(s2)); //0
System.out.println(s1.compareTo(s3)); //1(because s1>s3)
25
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
System.out.println(s3.compareTo(s1)); //-1(because s3 < s1 )
}
}
String s1="hello";
String s2="hello";
String s3="meklo";
String s4="hemlo";
System.out.println(s1.compareTo(s2));
System.out.println(s1.compareTo(s3));
System.out.println(s1.compareTo(s4));
s1.concat("is immutable");
System.out.println(s1);
System.out.println(s1);
26
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Java String contains
The java string contains() method searches the sequence of characters in this string. It
returns true if sequence of char values are found in this string otherwise returns false.
class ContainsExample
System.out.println(name.contains("about"));
System.out.println(name.contains("hello"));
}
ARRAYLIST IN JAVA
27
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Java ArrayList Methods
1. add( Object o): This method adds an object o to the arraylist.
2. add(int index, Object o): It adds the object o to the array list at the given index.
3. remove(Object o): Removes the object o from the ArrayList.
4. remove(int index): Removes element from a given index.
5. int indexOf(Object o): Gives the index of the object o. If the element is not found in the
list then this method returns the value -1.
6. Object get(int index): It returns the object of list which is present at the specified index.
7. int size(): It gives the size of the ArrayList – Number of elements of the list.
8. clear(): It is used for removing all the elements of the array list in one go. The below code
will remove all the elements of ArrayList whose object is obj.
9. Object clone(): This method is used to return a shallow copy of an ArrayList.
10. boolean addAll(Collection C): This method is used to append all the elements from a
specific collection to the end of the mentioned list, in such a order that the values are
returned by the specified collection’s iterator.
11. boolean addAll(int index, Collection C): Used to insert all of the elements starting at the
specified position from a specific collection into the mentioned list.
class Veglist
veg.add("onion");
veg.add("tomato");
veg.add("brinjal");
veg.add("drumstick");
veg.add("ginger");
System.out.println(veg);
Collections.sort(veg);
System.out.println(veg);
28
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
for(int i=0;i<veg.size();i++)
String v=veg.get(i).toString();
if(v.startsWith("b"))
System.out.println(v);
import java.util.*;
29
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Object Cloning in Java
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.
Although Object.clone() has some design issues but it is still a popular and easy way of
copying objects. Following is a list of advantages of using clone() method:
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.
Object.clone() is protected, so we have to provide our own clone() and indirectly call
Object.clone() from it.
int a = 10;
int b = 20;
void get()
{
System.out.println(a);
System.out.println(b);
}
30
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
TestClone ob1 = new TestClone();
ob1.get(); // 10,20
ob2.a = 100;
ob2.b = 200;
ob2.get(); // 100,200
Example2:
int rollno;
String name;
this.rollno=rollno;
this.name=name;
Student s2=(Student)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
31
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Access Modifiers
Access modifiers are simply a keyword in Java that provides accessibility of a class
and its member. They set the access level to methods, variable, classes and constructors.
public
default
protected
private
public
The member with public modifiers can be accessed by any classes. The public methods,
variables or class have the widest scope.
default
When we do not mention any access modifier, it is treated as default. It is accessible only
within same package.
int a = 25;
String str = "Java";
boolean m1()
{
return true;
}
protected
The protected modifier is used within same package. It lies between public and
default access modifier. It can be accessed outside the package but through inheritance
only.
A class cannot be protected.
32
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Example: Sample program for protected access modifier
class Employee
{
protected int id = 101;
protected String name = "Jack";
}
public class ProtectedDemo extends Employee
{
private String dept = "Networking";
public void display()
{
System.out.println("Employee Id : "+id);
System.out.println("Employee name : "+name);
System.out.println("Employee Department : "+dept);
}
public static void main(String args[])
{
ProtectedDemo pd = new ProtectedDemo();
pd.display();
}}
Output:
Employee Id : 101
Employee name : Jack
Employee Department : Networking
private
The private methods, variables and constructor are not accessible to any other class. It is
the most restrictive access modifier. A class except a nested class cannot be private.
33
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
Output:
Private int a = 101
String s = TutorialRide
101 TutorialRide
private Yes No No No
34
Mrs. V.Saraswathi AP/CSE