Nothing Special   »   [go: up one dir, main page]

Aoops Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 31

CS18304 ADVANCED OOPS UNIT II

UNIT II INHERITANCE AND INTERFACES


Defining classes in Java – constructors, methods -access specifiers - static members - Inheritance –
Super classes- sub classes –Protected members – constructors in sub classes- the Object class –
abstract classes and methods- final methods and classes –- Object cloning -inner classes
INHERITANCE

How do you implement multiple inheritances in Java? Explain. (4)


Explain the types of inheritance in java with examples. (13)

The properties of base class will be reused in derived class is called as inheritance. The old
1.
class is known as a base class or super class or parent class, and the new class is known as
subclass or derived class or child class. By using extends keyword the properties of super class
will be reused in sub class.
Types of Inheritance:
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance.
4. Multiple Inheritances. (Java does not support it, but achieved using interface)

Important facts about inheritance in Java


• Superclass can only be one: A superclass can have any number of subclasses. But a
subclass can have only one superclass. This is because Java does not support multiple
inheritance with classes. Although with interfaces, multiple inheritance is supported
by java.
• Inheriting Constructors: A subclass inherits all the members (fields, methods, and
nested classes) from its superclass. Constructors are not members, so they are not
inherited by subclasses, but the constructor of the superclass can be invoked from the
subclass.
• Private member inheritance: A subclass does not inherit the private members of its
parent class. However, if the superclass has public or protected methods(like getters
and setters) for accessing its private fields, these can also be used by the subclass.
• Default superclass: Except Object class, which has no superclass, every class has one
and only one direct superclass (single inheritance). In the absence of any other explicit
superclass, every class is implicitly a subclass of Object class.

What all can be done in a Subclass?


In sub-classes we can inherit members as is, replace them, hide them, or supplement them
with new members:
• The inherited fields can be used directly, just like any other fields.
• We can declare new fields in the subclass that are not in the superclass.
• The inherited methods can be used directly as they are.
• We can write a new instance method in the subclass that has the same signature as the
one in the superclass, thus overriding it (as in example above, toString() method is
overridden).
• We can write a new static method in the subclass that has the same signature as the
one in the superclass, thus hiding it.
• We can declare new methods in the subclass that are not in the superclass.
• We can write a subclass constructor that invokes the constructor of the superclass,
either implicitly or by using the keyword super.

II YEAR CSE 1
CS18304 ADVANCED OOPS UNIT II

Why use inheritance in java


• For Method Overriding (so runtime polymorphism can be achieved).
• For Code Reusability.

4.9.1 Single Inheritance


Single Inheritance has only one super class and one sub class. The below diagram shows
that A is a super class and B is a sub class. Here the properties of class A will be reused in class
B.
Syntax:
Class superclass
{
//body of the class
}

Class subclass extends superclass


{
//body of the class
}
Example:
Class A
{
public void methodA()
{
System.out.println("Base class method");
} OUTPUT:
}
Base class method
Class B extends A
{ Child class method
public void methodB()
{
System.out.println("Child class method");
}
}

Class Demo
{
public static void main(String args[])
{
B obj = new B();
obj.methodA(); //calling super class method
obj.methodB(); //calling Sub class method
}
}

II YEAR CSE 2
CS18304 ADVANCED OOPS UNIT II

4.9.2 Multilevel Inheritance


1. How do you implement multilevel inheritances in Java? Explain. (4) (N/D 15)

When a class extends a class, which extends another class then this is called
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.
Syntax:
class SuperClass
{
//body of the class
}
Class SubClassOne extends SuperClass
{
//body of the class
}
Class SubClassTwo extends SubClassOne
{
//body of the class
}
Example
class A
{
public void methodA()
{
System.out.println("Class A method");
}
}

class B extends A
OUTPUT:
{
public void methodB() Class A Method
{ Class B Method
System.out.println("class B method"); Class C Method
}
}

class C extends B
{
public void methodC()
{
System.out.println("class C method");
}
}

class Demo {
public static void main(String args[])
{
C obj = new C();
obj.methodA(); //calling grand parent class method
obj.methodB(); //calling parent class method
obj.methodC(); //calling local method
}
}

II YEAR CSE 3
CS18304 ADVANCED OOPS UNIT II

Example 2
import java.io.*;
import java.util.Scanner;

class StudentBasicInfo
{
int regno;
String name;
Scanner sc=new Scanner(System.in);

void getmethodA()
{
System.out.println("Enter the Name: ");
name=sc.next();
System.out.println("Enter the Register Number: ");
regno= sc.nextInt();
}

void displaymethodA()
{
System.out.println("Name: " + name);
System.out.println("Register Number: " + regno);
}
}

class StudentHSCMarks extends StudentBasicInfo


{
int tamil, english, maths, biology, phy, chem;

void getmethodB()
{
getmethodA();
System.out.println("Enter the Marks: ");
tamil= sc.nextInt();
english= sc.nextInt();
maths= sc.nextInt();
biology= sc.nextInt();
phy= sc.nextInt();
chem= sc.nextInt();
}
}

class StudentAvg extends StudentHSCMarks


{
int total;
float avg;

void calculate()
{
total=tamil+english+maths+biology+phy+chem;
avg=total/12;
}

void displaymethodB()
{

II YEAR CSE 4
CS18304 ADVANCED OOPS UNIT II

displaymethodA();
System.out.println("Total: " +total);
System.out.println("Average: " + avg);
}
}

class StudDemo
{
public static void main(String args[])throws IOException
{
StudentAvg obj = new StudentAvg();
obj.getmethodB();
obj.calculate();
obj.displaymethodB();
}
}

INPUT:

Enter the Name: Raj


Enter the Register Number: 12345
Enter the Marks:
120
120
120
120
120
120

OUTPUT:
Name: Raj
Register Number: 12345
Total: 720
Average: 60.00

II YEAR CSE 5
CS18304 ADVANCED OOPS UNIT II

Example 3:
import java.io.*;
import java.util.Scanner;

class employe
{
protected int emp_no;
protected String name;
protected int salary;
Scanner sc = new Scanner(System.in);

public void getemployeData()


{
System.out.println("\nEnter Employee No.:");
emp_no=sc.nextInt();
System.out.println("\nEnter Employee Name:");
name=sc.next();
System.out.println("\nEnter Employee Salary:");
salary=sc.nextInt();
}

public void emplo_data()


{
System.out.println("\nEmploy no.="+emp_no);
System.out.println("Name="+name);
System.out.println("Salary="+salary);
}
}

class manager extends employe


{
int reward;
public void getmanagerData()
{
getemployeData();
System.out.println("\nEnter Manager Reward:");
reward=sc.nextInt();
}

public void managerdata()


{
System.out.println("\nEmploy no.="+emp_no);
System.out.println("Name="+name);
System.out.println("Salary="+salary);

II YEAR CSE 6
CS18304 ADVANCED OOPS UNIT II

System.out.println("Reward="+reward);
}
}

class scientist extends manager


{
int perks;
public void getscientistData()
{
getemployeData();
System.out.println("\nEnter Scientist perks:");
perks=sc.nextInt();
}

public void scientistdata()


{
System.out.println("\nEmploy no.="+emp_no);
System.out.println("Name="+name);
System.out.println("Salary="+salary);
System.out.println("Perks="+perks);
}
}

class inheritance
{
public static void main(String args[])
{
scientist scient= new scientist();
scient.getemployeData();
scient.emplo_data();
scient.getmanagerData();
scient.managerdata();
scient.getscientistData();
scient.scientistdata();
}
}

II YEAR CSE 7
CS18304 ADVANCED OOPS UNIT II

4.9.3 Hierarchical Inheritance


When more than one classes inherit a same class then this is called hierarchical
inheritance. For example class B, C and D extends a same class A.

Example

class A
{
public void methodA()
{
System.out.println("method of Class A");
}
}
class B extends A
{
public void methodB()
{
System.out.println("method of Class B");
}
}
class C extends A
{
public void methodC()
{
System.out.println("method of Class C");
}
}
class D extends A
{
public void methodD()
{
System.out.println("method of Class D");
}
}
class Demo
{
public static void main(String args[])
{
B obj1 = new B();
C obj2 = new C();
D obj3 = new D();
obj1.methodA();
obj1.methodB();
obj2.methodC();
obj3.methodD();
}
}

Output:
method of Class A
method of Class B
method of Class C
method of Class D

II YEAR CSE 8
CS18304 ADVANCED OOPS UNIT II

THE SUPER KEYWORD

The super keyword is similar to this keyword. Following are the scenarios where the super
keyword is used.

• It is used to differentiate the members of superclass from the members of subclass,


if they have same names.
• It is used to invoke the superclass constructor from subclass.

class Super_class
{
int num = 20;

public void display()


{
System.out.println("This is the display method of superclass");
}
}

public class Sub_class extends Super_class


{
int num = 10;
public void display()
{
System.out.println("This is the display method of subclass");
}

public void my_method()


{
Sub_class sub = new Sub_class();
sub.display();
super.display();
System.out.println("value of the variable named num in sub class:"+ sub.num);
System.out.println("value of the variable named num in super class:"+ super.num);
}

public static void main(String args[])


{
Sub_class obj = new Sub_class();
obj.my_method();
}
}

Output
This is the display method of subclass
This is the display method of superclass
value of the variable named num in sub class:10
value of the variable named num in super class:20

Invoking Superclass Constructor

II YEAR CSE 9
CS18304 ADVANCED OOPS UNIT II

If a class is inheriting the properties of another class, the subclass automatically acquires the
default constructor of the superclass. But if you want to call a parameterized constructor of
the superclass, you need to use the super keyword as shown below.
super(values);

Example
class Superclass {
int age;

Superclass(int age) {
this.age = age;
}

public void getAge() {


System.out.println("The value of the variable named age in super class is: " +age);
}
}

public class Subclass extends Superclass {


Subclass(int age) {
super(age);
}

public static void main(String argd[]) {


Subclass s = new Subclass(24);
s.getAge();
}
}

Object class in Java


Object class is present in java.lang package. Every class in Java is directly or indirectly
derived from the Object class. If a Class does not extend any other class then it is direct child
class of Object and if extends other class then it is an indirectly derived. Therefore the Object
class methods are available to all Java classes. Hence Object class acts as a root of
inheritance hierarchy in any Java Program.

Methods of Object class


The Object class provides many methods. They are as follows:

1. protected Object clone() This method creates and returns a copy of this object.
2. boolean equals(Object obj) This method indicates whether some other object is
"equal to" this one.
3. protected void finalize() This method is called by the garbage collector on an object
when garbage collection determines that there are no more references to the object.
4. Class<?> getClass() This method returns the runtime class of this Object.
5. int hashCode() This method returns a hash code value for the object.
6. void notify() This method wakes up a single thread that is waiting on this object's
monitor.
7. void notifyAll() This method wakes up all threads that are waiting on this object's
monitor.
8. String toString() This method returns a string representation of the object.

II YEAR CSE 10
CS18304 ADVANCED OOPS UNIT II

9. void wait() This method causes the current thread to wait until another thread invokes
the notify() method or the notifyAll() method for this object.
10. void wait(long timeout) This method causes the current thread to wait until either
another thread invokes the notify() method or the notifyAll() method for this object,
or a specified amount of time has elapsed.
11. void wait(long timeout, int nanos) This method causes the current thread to wait until
another thread invokes the notify() method or the notifyAll() method for this object,
or some other thread interrupts the current thread, or a certain amount of real time has
elapsed.

Example: Object Clone

import java.util.GregorianCalendar; Output


Mon Sep 17 04:51:41 EEST 2017
public class ObjectDemo { Mon Sep 17 04:51:41 EEST 2017

public static void main(String[] args) {

// create a gregorian calendar, which is an object


GregorianCalendar cal = new GregorianCalendar();

// clone object cal into object y


GregorianCalendar y = (GregorianCalendar) cal.clone();

// print both cal and y


System.out.println("" + cal.getTime());
System.out.println("" + y.getTime());

}
}

Example: boolean equals(Object obj)

public class ObjectDemo {

public static void main(String[] args) { Output


false
// get an integer, which is an object true
Integer x = new Integer(50);

// get a float, which is an object as well


Float y = new Float(50f);

// check if these are equal,which is


// false since they are different class
System.out.println("" + x.equals(y));

// check if x is equal with another int 50


System.out.println("" + x.equals(50));
}
}

Example: protected void finalize()

II YEAR CSE 11
CS18304 ADVANCED OOPS UNIT II

import java.util.*;

public class ObjectDemo extends GregorianCalendar {

public static void main(String[] args) {


Output
try {
Sat Sep 22 00:27:21 EEST 2012
// create a new ObjectDemo object
Finalizing...
ObjectDemo cal = new ObjectDemo();
Finalized.
// print current time
System.out.println("" + cal.getTime());

// finalize cal
System.out.println("Finalizing...");
cal.finalize();
System.out.println("Finalized.");

} catch (Throwable ex) {


ex.printStackTrace();
}
}
}

Example: getClass()
import java.util.GregorianCalendar;

public class ObjectDemo {

public static void main(String[] args) {

// create a new ObjectDemo object


GregorianCalendar cal = new GregorianCalendar();

// print current time


System.out.println("" + cal.getTime());

// print the class of cal


System.out.println("" + cal.getClass());

// create a new Integer


Integer i = new Integer(5); Output
Sat Sep 22 00:31:24 EEST 2012
// print i class
System.out.println("" + i); java.util.GregorianCalendar
5
// print the class of i class java.lang.Integer
System.out.println("" + i.getClass());
}
}

Example: int hashCode()


public class ObjectDemo {

public static void main(String[] args) {

// create a new ObjectDemo object


GregorianCalendar cal = new GregorianCalendar();

// print current time

II YEAR CSE 12
CS18304 ADVANCED OOPS UNIT II

System.out.println("" + cal.getTime());

// print a hashcode for cal


System.out.println("" + cal.hashCode());

// create a new Integer Output


Integer i = new Integer(5); Sat Sep 22 00:35:34 EEST 2012
-458465658
// print i 5
System.out.println("" + i); 5
// print hashcode for i
System.out.println("" + i.hashCode());
}
}

Example: String toString()


Output
50
import java.util.ArrayList; [50, Hello World]

public class ObjectDemo {

public static void main(String[] args) {

// get an integer
Integer i = new Integer(50);

// get a list
ArrayList list = new ArrayList();

// add some elements in list


list.add(50);
list.add("Hello World");

// print their string representation


System.out.println("" + i.toString());
System.out.println("" + list.toString());
}
}

ABSTRACT CLASS & METHOD

2. Discuss about benefits of abstract class. (3) (A/M 17)

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).
Example abstract class
abstract class A{}

II YEAR CSE 13
CS18304 ADVANCED OOPS UNIT II

Abstract method
A method that is declared as abstract and does not have implementation is known as abstract
method.
abstract void printStatus();//no body and abstract

Example of abstract class that has abstract method


In this example, Bike the abstract class that contains only one abstract method run. It
implementation is provided by the Honda class.

abstract class Bike


{
abstract void run();
}
class Honda4 extends Bike
{
void run()
{
System.out.println("running safely..");
}
public static void main(String args[])
{
Bike obj = new Honda4();
obj.run();
}
}

Final Keyword In Java


The final keyword in java is used to restrict the user. The java final keyword can be used in
many context. Final can be:

1. variable
2. method
3. class

The final keyword can be applied with the variables, a final variable that have no value it is
called blank final variable or uninitialized final variable. It can be initialized in the
constructor only. The blank final variable can be static also which will be initialized in the
static block only. We will have detailed learning of these. Let's first learn the basics of final
keyword.

1) Java final variable


If you make any variable as final, you cannot change the value of final variable(It will be
constant).

II YEAR CSE 14
CS18304 ADVANCED OOPS UNIT II

Example of final variable

There is a final variable speedlimit, we are going to change the value of this variable, but It
can't be changed because final variable once assigned a value can never be changed.

class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Output:Compile Time Error

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

public static void main(String args[]){


Honda honda= new Honda();
honda.run();
}
}

Output:Compile Time Error

Java final class


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

II YEAR CSE 15
CS18304 ADVANCED OOPS UNIT II

final class Bike{}

class Honda1 extends Bike{


void run()
{
System.out.println("running safely with 100kmph");
}

public static void main(String args[]){


Honda1 honda= new Honda1();
honda.run();
}
}
Output:Compile Time Error

Is final method inherited?


Yes, final method is inherited but you cannot override it. For Example:
class Bike{
final void run(){System.out.println("running...");}
}
class Honda2 extends Bike{
public static void main(String args[]){
new Honda2().run();
}
}
Output:running...

What is blank or uninitialized final variable?

A final variable that is not initialized at the time of declaration is known as blank final
variable.

If you want to create a variable that is initialized at the time of creating object and once
initialized may not be changed, it is useful. For example PAN CARD number of an
employee.

It can be initialized only in constructor.

Example of blank final variable


class Student{
int id;
String name;
final String PAN_CARD_NUMBER;
...

II YEAR CSE 16
CS18304 ADVANCED OOPS UNIT II

Can we initialize blank final variable?


Yes, but only in constructor. For example:
class Bike10{
final int speedlimit;//blank final variable

Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}

public static void main(String args[]){


new Bike10();
}
}
Output: 70

static blank final variable


A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static block.
class A{
static final int data;//static blank final variable
static{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}

What is final parameter?


If you declare any parameter as final, you cannot change the value of it.
class Bike11{
int cube(final int n){
n=n+2;//can't be changed as n is final
n*n*n;
}
public static void main(String args[]){
Bike11 b=new Bike11();
b.cube(5);
}
}

II YEAR CSE 17
CS18304 ADVANCED OOPS UNIT II

Output: Compile Time Error

OBJECT CLONING
Object cloning refers to creation of exact copy of an object. It creates a new instance of the
class of current object and initializes all its fields with exactly the contents of the
corresponding fields of this 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

Why use clone() method ?


The clone() method saves the extra processing task for creating the exact copy of an object.
If we perform it by using the new keyword, it will take a lot of processing time to be
performed that is why we use object cloning.

Advantage of Object cloning


• You don't need to write lengthy and repetitive codes. Just use an abstract class with a
4- or 5-line long clone() method.
• It is the easiest and most efficient way for copying objects, especially if we are
applying it to an already developed or an old project. Just define a parent class,
implement Cloneable in it, provide the definition of the clone() method and the task
will be done.
• Clone() is the fastest way to copy array.

Disadvantage of Object cloning


• To use the Object.clone() method, we have to change a lot of syntaxes to our code,
like implementing a Cloneable interface, defining the clone() method and handling
CloneNotSupportedException, and finally, calling Object.clone() etc.
• We have to implement cloneable interface while it doesn?t have any methods in it.
We just have to use it to tell the JVM that we can perform clone() on our object.
• Object.clone() is protected, so we have to provide our own clone() and indirectly call
Object.clone() from it.
• Object.clone() doesn?t invoke any constructor so we don?t have any control over
object construction.
• If you want to write a clone method in a child class then all of its superclasses should
define the clone() method in them or inherit it from another parent class. Otherwise,
the super.clone() chain will fail.
• Object.clone() supports only shallow copying but we will need to override it if we
need deep cloning.

class Student18 implements Cloneable{


int rollno;
String name;

Student18(int rollno,String name){


this.rollno=rollno;
this.name=name;
}

public Object clone()throws CloneNotSupportedException{


return super.clone();

II YEAR CSE 18
CS18304 ADVANCED OOPS UNIT II

public static void main(String args[]){ Output:


try{ 101 amit
Student18 s1=new Student18(101,"amit"); 101 amit

Student18 s2=(Student18)s1.clone();

System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);

}catch(CloneNotSupportedException c){}

}
}

Shallow Copy Deep Copy


Cloned Object and original object are not Cloned Object and original object are 100%
100% disjoint. disjoint.
Any changes made to cloned object will be Any changes made to cloned object will not
reflected in original object or vice versa. be reflected in original object or vice versa.
Default version of clone method creates the To create the deep copy of an object, you
shallow copy of an object. have to override clone method.
Shallow copy is preferred if an object has Deep copy is preferred if an object has
only primitive fields. references to other objects as fields.
Shallow copy is fast and also less expensive. Deep copy is slow and very expensive.

INNER CLASSES (NON-STATIC NESTED CLASSES)


Inner classes are a security mechanism in Java. We know a class cannot be associated with
the access modifier private, but if we have the class as a member of other class, then the
inner class can be made private. And this is also used to access the private members of a
class.
Inner classes are of three types depending on how and where you define them. They are −
• Inner Class
• Method-local Inner Class
• Anonymous Inner Class

INNER CLASS
Creating an inner class is quite simple. You just need to write a class within a class. Unlike a
class, an inner class can be private and once you declare an inner class private, it cannot be
accessed from an object outside the class.
Following is the program to create an inner class and access it. In the given example, we
make the inner class private and access the class through a method.

Example
class Outer_Demo {
int num;

II YEAR CSE 19
CS18304 ADVANCED OOPS UNIT II

// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}
}

// Accessing he inner class from the method within


void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}
}

public class My_class {

public static void main(String args[]) {


// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Accessing the display_Inner() method.


outer.display_Inner();
}
}

Here you can observe that Outer_Demo is the outer class, Inner_Demo is the inner class,
display_Inner() is the method inside which we are instantiating the inner class, and this
method is invoked from the main method.
If you compile and execute the above program, you will get the following result −

Output
This is an inner class.

Accessing the Private Members


As mentioned earlier, inner classes are also used to access the private members of a class.
Suppose, a class is having private members to access them. Write an inner class in it, return
the private members from a method within the inner class, say, getValue(), and finally from
another class (from which you want to access the private members) call the getValue()
method of the inner class.
To instantiate the inner class, initially you have to instantiate the outer class. Thereafter,
using the object of the outer class, following is the way in which you can instantiate the inner
class.
Outer_Demo outer = new Outer_Demo();
Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
The following program shows how to access the private members of a class using inner class.

Example
class Outer_Demo {
// private variable of the outer class
private int num = 175;

// inner class
public class Inner_Demo {
public int getNum() {
System.out.println("This is the getnum method of the inner
class");
return num;

II YEAR CSE 20
CS18304 ADVANCED OOPS UNIT II

}
}
}

public class My_class2 {

public static void main(String args[]) {


// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();

// Instantiating the inner class


Outer_Demo.Inner_Demo inner = outer.new Inner_Demo();
System.out.println(inner.getNum());
}
}
If you compile and execute the above program, you will get the following result −
Output
The value of num in the class Test is: 175

Method-local Inner Class


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.
A method-local inner class can be instantiated only within the method where the inner class is
defined. The following program shows how to use a method-local inner class.
Example
public class Outerclass {
// instance method of the outer class
void my_Method() {
int num = 23;

// method-local inner class


class MethodInner_Demo {
public void print() {
System.out.println("This is method inner class "+num);
}
} // end of inner class

// Accessing the inner class


MethodInner_Demo inner = new MethodInner_Demo();
inner.print();
}

public static void main(String args[]) {


Outerclass outer = new Outerclass();
outer.my_Method();
}
}
If you compile and execute the above program, you will get the following result −
Output
This is method inner class 23

Anonymous Inner Class


An inner class declared without a class name is known as an anonymous inner class. In case
of anonymous inner classes, we declare and instantiate them at the same time. Generally, they

II YEAR CSE 21
CS18304 ADVANCED OOPS UNIT II

are used whenever you need to override the method of a class or an interface. The syntax of
an anonymous inner class is as follows −
Syntax
AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};
The following program shows how to override the method of a class using anonymous inner
class.
Example
abstract class AnonymousInner {
public abstract void mymethod();
}

public class Outer_class {

public static void main(String args[]) {


AnonymousInner inner = new AnonymousInner() {
public void mymethod() {
System.out.println("This is an example of anonymous inner
class");
}
};
inner.mymethod();
}
}
If you compile and execute the above program, you will get the following result −
Output
This is an example of anonymous inner class
In the same way, you can override the methods of the concrete class as well as the interface
using an anonymous inner class.

Anonymous Inner Class as Argument


Generally, if a method accepts an object of an interface, an abstract class, or a concrete class,
then we can implement the interface, extend the abstract class, and pass the object to the
method. If it is a class, then we can directly pass it to the method.
But in all the three cases, you can pass an anonymous inner class to the method. Here is the
syntax of passing an anonymous inner class as a method argument −
obj.my_Method(new My_Class() {
public void Do() {
.....
.....
}
});
The following program shows how to pass an anonymous inner class as a method argument.
Example
// interface
interface Message {
String greet();
}

public class My_class {


// method which accepts the object of interface Message
public void displayMessage(Message m) {
System.out.println(m.greet() +

II YEAR CSE 22
CS18304 ADVANCED OOPS UNIT II

", This is an example of anonymous inner class as an argument");


}

public static void main(String args[]) {


// Instantiating the class
My_class obj = new My_class();

// Passing an anonymous inner class as an argument


obj.displayMessage(new Message() {
public String greet() {
return "Hello";
}
});
}
}
If you compile and execute the above program, it gives you the following result −
Output
Hello This is an example of anonymous inner class as an argument

Static Nested Class


A static inner class is a nested class which is a static member of the outer class. It can be
accessed without instantiating the outer class, using other static members. Just like static
members, a static nested class does not have access to the instance variables and methods of
the outer class. The syntax of static nested class is as follows −
Syntax
class MyOuter {
static class Nested_Demo {
}
}
Instantiating a static nested class is a bit different from instantiating an inner class. The
following program shows how to use a static nested class.
Example
public class Outer {
static class Nested_Demo {
public void my_method() {
System.out.println("This is my nested class");
}
}

public static void main(String args[]) {


Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
}
}
If you compile and execute the above program, you will get the following result −
Output
This is my nested class

ARRAY LISTS
Java ArrayList class uses a dynamic array for storing the elements. It inherits AbstractList
class and implements List interface.
The important points about Java ArrayList class are:
• Java ArrayList class can contain duplicate elements.
• Java ArrayList class maintains insertion order.

II YEAR CSE 23
CS18304 ADVANCED OOPS UNIT II

• Java ArrayList class is non synchronized.


• Java ArrayList allows random access because array works at the index basis.
• In Java ArrayList class, manipulation is slow because a lot of shifting needs to be
occurred if any element is removed from the array list.
Hierarchy of ArrayList class
As shown in above diagram, Java ArrayList class extends AbstractList class
which implements List interface. The List interface extends Collection and
Iterable interfaces in hierarchical order.
Constructors of Java ArrayList
• ArrayList( ) This constructor builds an empty array list.
• ArrayList(Collection c) This constructor builds an array list that is
initialized with the elements of the collection c.
• ArrayList(int capacity) This constructor builds an array list that has the
specified initial capacity. The capacity is the size of the underlying array
that is used to store the elements. The capacity grows automatically as
elements are added to an array list.
Methods of Java ArrayList
1. void add(int index, Object element) Inserts the specified element at the specified
position index in this list. Throws IndexOutOfBoundsException if the specified index
is out of range (index < 0 || index > size()).
2. boolean add(Object o) Appends the specified element to the end of this list.
3. boolean addAll(Collection c) Appends all of the elements in the specified collection
to the end of this list, in the order that they are returned by the specified collection's
iterator. Throws NullPointerException, if the specified collection is null.
4. boolean addAll(int index, Collection c) Inserts all of the elements in the specified
collection into this list, starting at the specified position. Throws
NullPointerException if the specified collection is null.
5. void clear() Removes all of the elements from this list.
6. Object clone() Returns a shallow copy of this ArrayList.
7. boolean contains(Object o) Returns true if this list contains the specified element.
More formally, returns true if and only if this list contains at least one element e such
that (o==null ? e==null : o.equals(e)).
8. void ensureCapacity(int minCapacity) Increases the capacity of this ArrayList
instance, if necessary, to ensure that it can hold at least the number of elements
specified by the minimum capacity argument.
9. Object get(int index) Returns the element at the specified position in this list. Throws
IndexOutOfBoundsException if the specified index is out of range (index < 0 || index
>= size()).
10. int indexOf(Object o) Returns the index in this list of the first occurrence of the
specified element, or -1 if the List does not contain this element.
11. int lastIndexOf(Object o) Returns the index in this list of the last occurrence of the
specified element, or -1 if the list does not contain this element.

II YEAR CSE 24
CS18304 ADVANCED OOPS UNIT II

12. Object remove(int index) Removes the element at the specified position in this list.
Throws IndexOutOfBoundsException if the index out is of range (index < 0 || index
>= size()).
13. protected void removeRange(int fromIndex, int toIndex) Removes from this List
all of the elements whose index is between fromIndex, inclusive and toIndex,
exclusive.
14. Object set(int index, Object element) Replaces the element at the specified position
in this list with the specified element. Throws IndexOutOfBoundsException if the
specified index is out of range (index < 0 || index >= size()).
15. int size() Returns the number of elements in this list.
16. Object[] toArray() Returns an array containing all of the elements in this list in the
correct order. Throws NullPointerException if the specified array is null.
17. Object[] toArray(Object[] a) Returns an array containing all of the elements in this
list in the correct order; the runtime type of the returned array is that of the specified
array.
18. void trimToSize() Trims the capacity of this ArrayList instance to be the list's current
size.

Example
import java.util.*;
class TestCollection1{
public static void main(String args[]){

ArrayList<String>list=new ArrayList<String>();
list.add("Ravi");//Adding object in arraylist
list.add("Vijay"); OUTPUT:
list.add("Ravi"); Ajay
list.add(1,"Ajay"); Ravi
Vijay
ArrayList<String> al2=new ArrayList<String>(); Ravi
al2.add("Sonoo"); Sonoo
al2.add("Hanumat"); Hanumat
al.addAll(al2);//adding second list in first list

//Traversing list through Iterator


Iterator itr=list.iterator();
while(itr.hasNext()){
System.out.println(itr.next());

// Iterating Collection through for-each loop


for(String obj:al)
System.out.println(obj);
}
}
}

Example 2:
import java.util.*;
class Book {

II YEAR CSE 25
CS18304 ADVANCED OOPS UNIT II

int id;
String name,author,publisher;
int quantity;
public Book(int id, String name, String author, String publisher, int
quantity)
{
this.id = id;
this.name = name;
this.author = author;
this.publisher = publisher;
this.quantity = quantity;
}
}

public class ArrayListExample


{
public static void main(String[] args)
{
//Creating list of Books
List<Book> list=new ArrayList<Book>();
//Creating Books
Book b1=new Book(101,"Let us C","Yashwant Kanetkar","BPB",8);
Book b2=new Book(102,"Data Communications & Networking","Forouzan","Mc Graw Hill",4);
Book b3=new Book(103,"Operating System","Galvin","Wiley",6);
//Adding Books to list
list.add(b1);
list.add(b2); OUTPUT
list.add(b3); 101 Let us C Yashwant Kanetkar BPB 8
//Traversing list 102 Data Communications & Networking Forouzan Mc Graw Hill 4
for(Book b:list) 103 Operating System Galvin Wiley 6
{
System.out.println(b.id+" "+b.name+" "+b.author+" "+b.publisher+" "+b.quantity);
}
}
}

Example 3
import java.util.*;
public class ArrayListDemo {

public static void main(String args[]) {


// create an array list
ArrayList al = new ArrayList();
System.out.println("Initial size of al: " + al.size());

// add elements to the array list


al.add("C");
al.add("A");
al.add("E");
al.add("B");
al.add("D");
al.add("F");
al.add(1, "A2");
System.out.println("Size of al after additions: " + al.size());

II YEAR CSE 26
CS18304 ADVANCED OOPS UNIT II

// display the array list


System.out.println("Contents of al: " + al);

// Remove elements from the array list


al.remove("F");
al.remove(2);
System.out.println("Size of al after deletions: " + al.size());
System.out.println("Contents of al: " + al);
}
}
Output
Initial size of al: 0
Size of al after additions: 7
Contents of al: [C, A2, A, E, B, D, F]
Size of al after deletions: 5
Contents of al: [C, A2, E, B, D]

5.5 STRINGS
• 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.
• 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
• Strings can be create using string class.
• Example:
String s1="Welcome";
Here
String is predefined class,
S1 is object of String,
• Strings can also be created using constructors
String s=new String("Welcome");

5.5.1 Java String class methods


The java.lang.String class provides many useful methods to perform operations on
sequence of char values.
`
No. Method Description
1 char charAt(int index) returns char value for the particular index
2 int length() returns string length
3 String substring(int beginIndex) returns substring for given begin index
String substring(int beginIndex, int returns substring for given begin index
4
endIndex) and end index
5 boolean equals(Object another) checks the equality of string with object
6 boolean isEmpty() checks if string is empty
7 String concat(String str) concatinates specified string
replaces all occurrences of specified char
8 String replace(char old, char new)
value

II YEAR CSE 27
CS18304 ADVANCED OOPS UNIT II

String replace(CharSequence old, replaces all occurrences of specified


9
CharSequence new) CharSequence
returns trimmed string omitting leading
10 String trim()
and trailing spaces
11 String toLowerCase(String str) Covert lowercase to uppercase.
12 String toUpperCase(String str) Covert uppercase to lowercase.
import java.io.*;
import java.lang.String;
public class StringExample
{
public static void main(String[] args)
{
String str = " Have a nice day ";
// convert string into Lower case
String Lowercase = str.toLowerCase();
System.out.println("Lower case String: " + Lowercase);

// convert string into upper case


String Uppercase = str.toUpperCase();
System.out.println("Upper case String : " + Uppercase);

// Find length of the given string


System.out.println("Length of the given string: " + str.length());

// Trim the given string i.e. remove all first and last the spaces from the string
String tempstr = " String trimming example ";
System.out.println("String before trimming: " + tempstr);
System.out.println("String after trimming: " + tempstr.trim());

// Find the character at the given index from the given string
System.out.println("Character at the index 7 is: " + str.charAt(7));

// find the substring between two index range


System.out.println("String between index 7 to 10 is : "+ str.substring(7, 10));

// replace the character with another character


System.out.println("String after replacement : "+ str.replace('a', 'Y'));

// replace the substring with another substring


System.out.println("String after replacement : " + str.replace("day", "morning"));
}
}
OUTPUT:
C:\Program Files\Java\jdk1.5.0\bin>java StringExample
Lower case String: have a nice day
Upper case String : HAVE A NICE DAY
Length of the given string: 15
String before trimming: String trimming example
String after trimming: String trimming example
Character at the index 7 is: n

II YEAR CSE 28
CS18304 ADVANCED OOPS UNIT II

String between index 7 to 10 is : nic


String after replacement : HYve Y nice dYy
String after replacement : Have a nice morning
Example 2:
import java.io.*; OUTPUT:
import java.lang.String; C:\Program Files\Java\jdk1.5.0\bin>java Demo
public class Demo hello java
{ HELLO JAVA
public static void main(String[] args) 11
{ Hello Java
String obj = " Hello Java"; 11
System.out.println(obj.toLowerCase()); J
System.out.println(obj.toUpperCase()); Hello World
System.out.println(obj.length()); Jav
System.out.println(obj.trim());
System.out.println(obj.length());
System.out.println(obj.charAt(7));
System.out.println(obj.replace("Java", "World"));
System.out.println(obj.substring(6, 10));
}
}

5.5.2 STRING BUFFER CLASS


The StringBuffer is a class which is alternative to the String class. But StringBuffer class is more
flexible to use than String class.That means, using StringBuffer we can insert some component to the
existing string or modify the existing string but in case of String class once the string is defined then it
remains fixed.
5.5.3 Java StringBuffer class methods
No. Method Description
1 append(String str) Appends the String to the buffer
2 capacity() It returns the capacity of the string buffer
It insert the character at the position specified by the
3 insert(int offset, char ch)
offset
replace(int Start,int end,
4 It replaces the character specified by the new string
String str)
It deletes the character from the string specified by the
5 delete(int start,int end)
starting and ending index.
6 reverse() The character sequence is reversed
7 length() It returns the length of the string buffer
It returns a specific character from the sequence which is
8 charAt(int index)
specified by the index.
setCharAt(int index, char The character specified by the index from the stringbuffer
9
ch) is set to ch
10 setLengthIint new_len) It sets the length of the string buffer.

II YEAR CSE 29
CS18304 ADVANCED OOPS UNIT II

1) StringBuffer append() & length() method


class StringBufferExample{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.append("Java"); //now original string is changed
System.out.println(sb); //prints Hello Java
}
}
2) StringBuffer insert() method
class StringBufferExample2{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello ");
sb.insert(1,"Java"); //now original string is changed
System.out.println(sb); //prints HJavaello
int length = sb.length();
System.out.println(length); //prints 4
}
}
3) StringBuffer replace() method
class StringBufferExample3{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.replace(1,3,"Java");
System.out.println(sb); //prints HJavalo
}
}
4) StringBuffer delete() method
class StringBufferExample4{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.delete(1,3);
System.out.println(sb); //prints Hlo
}
}
5) StringBuffer reverse() method
class StringBufferExample5{
public static void main(String args[]){
StringBuffer sb=new StringBuffer("Hello");
sb.reverse();
System.out.println(sb); //prints olleH
}
}
6) StringBuffer capacity() method
The capacity() method of StringBuffer class returns the current capacity of the buffer. The default
capacity of the buffer is 16. If the number of character increases from its current capacity, it increases
the capacity by (oldcapacity*2)+2. For example if your current capacity is 16, it will be (16*2)+2=34.
class StringBufferExample6{
public static void main(String args[]){
StringBuffer sb=new StringBuffer();
System.out.println(sb.capacity()); //default 16
sb.append("Hello");

II YEAR CSE 30
CS18304 ADVANCED OOPS UNIT II

System.out.println(sb.capacity()); //now 16
sb.append("java is my favourite language");
System.out.println(sb.capacity()); //now (16*2)+2=34 i.e (oldcapacity*2)+2
}
}

Example 2:
import java.io.*;
import java.lang.*;
class Demo
{
public static void main(String[] args)
{
StringBuffer obj = new StringBuffer("Hello ");
System.out.println(obj.length());
System.out.println(obj.append("Java"));
System.out.println(obj.length());
System.out.println(obj.delete(0,5));
System.out.println(obj.insert(0,"Hello"));
System.out.println(obj.charAt(7));
System.out.println(obj.replace(6,10,"World"));
System.out.println(obj.reverse());
}
}
OUTPUT:
C:\Program Files\Java\jdk1.5.0\bin>java Demo
6
Hello Java
10
Java
Hello Java
a
Hello World
dlroW olleH

II YEAR CSE 31

You might also like