Aoops Unit 2
Aoops Unit 2
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)
II YEAR CSE 1
CS18304 ADVANCED OOPS UNIT II
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
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);
}
}
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();
}
}
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:
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);
II YEAR CSE 6
CS18304 ADVANCED OOPS UNIT II
System.out.println("Reward="+reward);
}
}
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
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 is similar to this keyword. Following are the scenarios where the super
keyword is used.
class Super_class
{
int num = 20;
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
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;
}
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.
}
}
II YEAR CSE 11
CS18304 ADVANCED OOPS UNIT II
import java.util.*;
// finalize cal
System.out.println("Finalizing...");
cal.finalize();
System.out.println("Finalized.");
Example: getClass()
import java.util.GregorianCalendar;
II YEAR CSE 12
CS18304 ADVANCED OOPS UNIT II
System.out.println("" + cal.getTime());
// get an integer
Integer i = new Integer(50);
// get a list
ArrayList list = new ArrayList();
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
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.
II YEAR CSE 14
CS18304 ADVANCED OOPS UNIT II
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
class Bike{
final void run(){System.out.println("running");}
}
II YEAR CSE 15
CS18304 ADVANCED OOPS UNIT II
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.
II YEAR CSE 16
CS18304 ADVANCED OOPS UNIT II
Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
II YEAR CSE 17
CS18304 ADVANCED OOPS UNIT II
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
II YEAR CSE 18
CS18304 ADVANCED OOPS UNIT II
Student18 s2=(Student18)s1.clone();
System.out.println(s1.rollno+" "+s1.name);
System.out.println(s2.rollno+" "+s2.name);
}catch(CloneNotSupportedException c){}
}
}
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");
}
}
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.
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
}
}
}
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();
}
II YEAR CSE 22
CS18304 ADVANCED OOPS UNIT II
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
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
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;
}
}
Example 3
import java.util.*;
public class ArrayListDemo {
II YEAR CSE 26
CS18304 ADVANCED OOPS UNIT II
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");
II YEAR CSE 27
CS18304 ADVANCED OOPS UNIT II
// 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));
II YEAR CSE 28
CS18304 ADVANCED OOPS UNIT II
II YEAR CSE 29
CS18304 ADVANCED OOPS UNIT II
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