0% found this document useful (0 votes)
25 views

Unit 2 (Oops)

Uploaded by

rambigboss1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
25 views

Unit 2 (Oops)

Uploaded by

rambigboss1234
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

CS8392-OOPS UNIT-II

UNIT II INHERITANCE AND INTERFACES

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

 Application development time is less.


 Application take less memory.
 Application execution time is less.
 Redundancy (repetition) of the code is reduced or minimized so that we get
consistence results and less storage cost.
1
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II

Types of Inheritance
 Single inheritance
 Multilevel inheritance
 Hierarchical inheritance
 Multiple inheritance

Example

class Calculation {
int z;

public void addition(int x, int y) {


z = x + y;
System.out.println("The sum of the given numbers:"+z);
}

public void Subtraction(int x, int y) {


z = x - y;
System.out.println("The difference between the given numbers:"+z);
}
}
2
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II

public class My_Calculation extends Calculation {


public void multiplication(int x, int y) {
z = x * y;
System.out.println("The product of the given numbers:"+z);
}
public static void main(String args[]) {
int a = 20, b = 10;
My_Calculation demo = new My_Calculation();
demo.addition(a, b);
demo.Subtraction(a, b);
demo.multiplication(a, b);
}
}
Output
The sum of the given numbers:30
The difference between the given numbers:10
The product of the given numbers:200

Multilevel Inheritance

Multilevel inheritance is a mechanism where one class can be inherited from a


derived class thereby making the derived class the base class for the new class.
Example: Sample program for 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.

Fig: Hierarchical Inheritance


Sample program for 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.

Fig: Multiple Inheritance

Example: Sample program for multiple inheritance

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 and Inheritance

interface Inf1
{
public void method1();
}
interface Inf2 extends Inf1
{
public void method2();
}
public class Demo implements Inf2
{

public void method1()


{
System.out.println("method1");
}
public void method2()
{
System.out.println("method2");
}
public static void main(String args[])
{
Inf2 obj = new Demo();
obj.method2();
}
}
7
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II

SUPER KEYWORD IN JAVA


The super keyword in java is a reference variable which is used to refer immediate parent
class object.

Usage of java super Keyword


1. super can be used to refer immediate parent class instance variable.
2. super can be used to invoke immediate parent class method.
3. super() can be used to invoke immediate parent class constructor.
Type 1) super.<variable_name> to invoke Parent class variable
class Parentclass class Employee
{ {
int num=100; float salary=10000;
} }
class Subclass extends Parentclass class HR extends Employee
{ {
int num=110; float salary=20000;
void printNumber( ) void display()
{ {
//Super.variable_name System.out.println("Salary "+
System.out.println(super.num); super.salary );
System.out.println(num); //print base class salary
} }
public static void main(String args[]) }
{ class Supervarible
Subclass obj= new Subclass(); {
obj.printNumber(); public static void main(String[] args)
} {
} HR obj=new HR();
Output: 100 obj.display();
110 }
}
Output
Salary: 10000.0
8
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II

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

Program:2 (super can be used to invoke immediate parent class method.)


class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}
class Faculty extends Student
{
void message()
{
System.out.println("Good Morning Students");
}
void display()
{
message(); //will invoke or call current class message() method
super.message(); //will invoke or call parent class message() method
9
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
}
public static void main(String args[])
{
Student s=new Student();
s.display();
}
}
Output : Good Morning Students
Good Morning Sir
3) super() to invoke constructor of parent class
Program1:

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 CLASS & METHODS


Abstraction
Abstraction is the technique of hiding the implementation details and showing only
functionality to the user.
For example, when we call any person we just dial the numbers and are least bothered
about the internal process involved.
Abstract class
 A class that can contain abstract keyword is known as an abstract class.
 Abstract methods do not have body.
 It forces the user to extend the implementation rather than modification.
 An abstract class cannot be instantiated.
Syntax : abstract class class_name { }

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

Abstraction is an important feature of OOPS. It means hiding complexity. Abstract


class is used to provide abstraction. Although it does not provide 100% abstraction because
it can also have concrete method. Lets see how abstract class is used to provide abstraction.

abstract class Vehicle


{
public abstract void engine();
}
public class Car extends Vehicle
{
public void engine()
{ //car engine implementation

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

Program: refer the class work

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.

An interface is similar to a class in the following ways −

 An interface can contain any number of methods.


 An interface is written in a file with a .java extension, with the name of the interface
matching the name of the file.
 The byte code of an interface appears in a .class file.
 Interfaces appear in packages, and their corresponding bytecode file must be in a
directory structure that matches the package name.

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

A class uses the implements keyword to implement an interface. The implements


keyword appears in the class declaration following the extends portion of the declaration.

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 {

public void eat() {


System.out.println("Mammal eats");
}

public void travel() {


System.out.println("Mammal travels");
}

public int noOfLegs() {


return 0;
}

public static void main(String args[]) {


MammalInt m = new MammalInt();
m.eat();
m.travel();
}
}

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

Abstract class Interface


Abstract class is a class which contain one Interface is a Java Object containing
or more abstract methods, which has to be method declaration but no implementation.
implemented by its sub classes. The classes which implement the Interfaces
must provide the method definition for all
the methods.
Abstract class is a Class prefix with an Interface is a pure abstract class which
abstract keyword followed by Class starts with interface keyword.
definition.
Abstract class can also contain concrete Whereas, Interface contains all abstract
methods. methods and final variable declarations.
Abstract classes are useful in a situation Interfaces are useful in a situation that all
that Some general methods should be properties should be implemented.
implemented and specialization behaviour
should be implemented by child classes.

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{

final int speedlimit=90; //final variable

void run(){

speedlimit=400;

public static void main(String args[]){

Bike obj=new Bike();

obj.run();
} } Output:Compile Time Error

2) Java final method

If you make any method as final, you cannot override it.

class Bike{

final void run()

{ System.out.println("running");

class Honda extends Bike{

void run()

System.out.println("running safely with 100kmph");

16
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
}

public static void main(String args[]){

Honda honda= new Honda();

honda.run();

Output:Compile Time Error

3) Java final class

If you make any class as final, you cannot extend it.

Example of final class

final class Bike{

class Honda extends Bike{

void run()

System.out.println("running safely with 100kmph");

public static void main(String args[]){

Honda h1= new Honda();

h1.run();

Output:Compile Time Error

Is final method inherited?

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{

final void run()

System.out.println("running...");}

class Honda extends Bike{

public static void main(String args[]){

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

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

Example of Inner class

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

Anonymous class (2 MARKS)


A class without any name is called Anonymous class In java Anonymous inner class can
be created by two ways:

1. Class (may be abstract or concrete).


2. Interface

abstract class Person interface Eatable


{ {
abstract void eat(); void eat();
} }
class TestAnonymousInner class TestAnnonymousInner1
{ {
public static void main(String args[]) public static void main(String args[])
{ {
Person p=new Person() Eatable e=new Eatable()
{ {
void eat() public void eat()
{ {
System.out.println("nice fruits"); System.out.println("nice fruits");
} }
}; };
p.eat(); e.eat();
} }
} }
interface Animal
{
void type();
}
public class ATest {
public static void main(String args[]) {
Animal an = new Animal(){ //Annonymous class created
public void type()
{
System.out.println("Anonymous animal");
}
};
an.type();
}
}
Output : Anonymous animal

22
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
JAVA STRING

An array of characters works same as 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.

What is String in java?

Generally, string is a sequence of characters. But in java, string is an object that


represents a sequence of characters. String class is used to create string object.
How to create String object?
There are two ways to create String object:

1. By string literal
2. By new keyword

1) String Literal
String s1="Welcome";
String s2="Hello";
2) By new keyword :

String s=new String("Welcome”)

Example Program:

public class StringExample{

public static void main(String args[]){

String s1="java"; //creating string by java string literal

char ch[]={'s','t','r','i','n','g','s'};

String s2=new String(ch); //converting char array to string

String s3=new String("example"); //creating java string by new keyword

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{

public static void main(String args[]){

String s="Sachin";

s.concat(" Tendulkar");//concat() - appends the string at the end

System.out.println(s); //will print Sachin because strings are immutable objects

} }

JAVA STRING COMPARE

There are three ways to compare string in java:

1. By equals() method
2. By = = operator
3. By compareTo() method

1) String compare by equals() 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{

public static void main(String args[]){


String s1="Sachin";
String s2="Sachin";
String s3=new String("Sachin");

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

2) String compare by == operator

class Teststringcomparison3{

public static void main(String args[]){

String s1="Sachin";

String s2="Sachin";

String s3=new String("Sachin");

System.out.println(s1==s2);//true (because both refer to same instance)

System.out.println(s1==s3);//false(because s3 refers to instance created in nonpool)

} }
Using == operator
String s1 = "Java";
String s2 = "Java";
String s3 = new string ("Java");
test(Sl == s2) //true
test(s1 == s3) //false

3) String compare by compareTo() method

Suppose s1 and s2 are two string variables.

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 )
}
}

Java String compareTo() method example

public class LastIndexOfExample{

public static void main(String args[]){

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));

Java String concat

public String concat(String anotherString)

public class ConcatExample{

public static void main(String args[]){

String s1="java string";

s1.concat("is immutable");

System.out.println(s1);

s1=s1.concat(" is immutable so assign it explicitly");

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.

public boolean contains(CharSequence sequence)

class ContainsExample

public static void main(String args[]){

String name="what do you know about me";

System.out.println(name.contains("do you know"));

System.out.println(name.contains("about"));

System.out.println(name.contains("hello"));

}
ARRAYLIST IN JAVA

ArrayList is a part of collection framework and is present in java.util package. It provides


us dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful
in programs where lots of manipulation in the array is needed.

 ArrayList inherits AbstractList class and implements List interface.


 ArrayList is initialized by a size, however the size can increase if collection grows
or shrunk if objects are removed from the collection.
 Java ArrayList allows us to randomly access the list.
 ArrayList can not be used for primitive types, like int, char, etc.

Constructors in Java ArrayList:

1. ArrayList(): This constructor is used to build an empty array list


2. ArrayList(Collection c): This constructor is used to build an array list initialized
with the elements from collection c
3. ArrayList(int capacity): This constructor is used to build an array list with initial
capacity being specified

The code to create generic ArrayList-

ArrayList<Integer> arrli = new ArrayList<Integer>();

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.

ArrayList Example in Java


import java.util.*;

class Veglist

public static void main(String args[])

ArrayList<String> veg=new ArrayList<String>();

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);

Example of Copying List elements to ArrayList

import java.util.*;

public class ListToArrayListExample


{

public static void main(String a[])


{
ArrayList<String> al = new ArrayList<String>();

//Adding elements to the ArrayList


al.add("Text 1");
al.add("Text 2");
al.add("Text 3");

System.out.println("ArrayList Elements are: "+al);

//Adding elements to a List


List<String> list = new ArrayList<String>();
list.add("Text 4");
list.add("Text 5");
list.add("Text 6");

//Adding all lements of list to ArrayList using addAll


al.addAll(list);
System.out.println("Updated ArrayList Elements: "+al);
}}
Output:
ArrayList Elements are: [Text 1, Text 2, Text 3]
Updated ArrayList Elements: [Text 1, Text 2, Text 3, Text 4, Text 5, Text 6]

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.

The clone() method is defined in the Object class.

Syntax of the clone() method is as follows:

protected Object clone() throws CloneNotSupportedException

Advantage of Object cloning

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.

Disadvantage of Object cloning

Object.clone() is protected, so we have to provide our own clone() and indirectly call
Object.clone() from it.

Example of clone() method (Object cloning)

public class TestClone implements Cloneable {

int a = 10;
int b = 20;
void get()
{
System.out.println(a);
System.out.println(b);
}

public static void main(String[] args) throws CloneNotSupportedException

30
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II
TestClone ob1 = new TestClone();

ob1.get(); // 10,20

TestClone ob2 = (TestClone) ob1.clone();

ob2.a = 100;

ob2.b = 200;

ob2.get(); // 100,200

Example2:

class Student implements Cloneable

int rollno;

String name;

Student (int rollno,String name)

this.rollno=rollno;

this.name=name;

public static void main(String args[])throws CloneNotSupportedException

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);

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.

Types of access modifier

There are 4 types of access modifiers available in Java.

 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.

Example: Sample program for public access modifier

public static void main(String args[])


{
// code
}

default

When we do not mention any access modifier, it is treated as default. It is accessible only
within same package.

Example: Sample program for default access modifier

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.

Example: Sample program for private access modifier

public class PrivateDemo


{
private int a = 101;
private String s = "TutorialRide";
public void show()
{
System.out.println("Private int a = "+a+"\nString s = "+s);
}
public static void main(String args[])
{
PrivateDemo pd = new PrivateDemo();
pd.show();
System.out.println(pd.a+" "+pd.s); }
}

33
Mrs. V.Saraswathi AP/CSE
CS8392-OOPS UNIT-II

Output:
Private int a = 101
String s = TutorialRide
101 TutorialRide

Table for Access Modifier

Access modifier In class In package Outside package by subclass Outside package

public Yes Yes Yes No

protected Yes Yes Yes No

default Yes Yes No No

private Yes No No No

34
Mrs. V.Saraswathi AP/CSE

You might also like