BCS306A OOP With Java Module-2 Notes
BCS306A OOP With Java Module-2 Notes
The data, or variables, defined within a class are called instance variables. The code is
contained within methods. Collectively, the methods and variables defined within a class are
called members of the class.
• First, you must declare a variable of the class type which is simply a variable that can
refer to an object.
• Second, you must acquire an actual, physical copy of the object and assign it to that
variable using the new operator. The new operator dynamically allocates memory for
an object and returns a reference to it where the address is stored.
OR
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Page 1
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
Object:
o Object is a real world entity.
o Object is a run time entity.
o Object is an entity which has state and behavior.
o Object is an instance of a class.
Page 2
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
A Simple Class
class Box {
double width;
double height;
double depth;
}
// This class declares an object of type Box.
Class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol); }
}
Introducing Methods
type name(parameter-list) {
// body of method
return value;
}
Methods define the interface to most classes. This allows the class implementer to hide the
specific layout of internal data structures behind cleaner method abstractions. Defining
methods provide access to data, you can also define methods that are used internally by the
class itself.
Class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
Page 3
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
}
}
class Demo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
vol = mybox1.volume();
System.out.println(―Volume is ― + vol);
vol = mybox2.volume();
System.out.println(―Volume is ― + vol);
}
}
CONSTRUCTORS:
A constructor initializes an object immediately upon creation. It has the same name as the class
in which it resides and is syntactically similar to a method.A constructor doesn’t have a return
type.The name of the constructor must be the same as the name of the class.Unlike methods,
constructors are not considered members of a class.
Default Constructor: It is a constructor which do not take any arguments.If you do not
define any constructor in your class, java generates one for you by default.
Class Box {
double width;
double height;
double depth;
Box()
{
System.out.println(―Constructing Box‖);
width = 10;
height = 10;
depth = 10;
}
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
double volume() {
return width * height * depth;
}
}
class demo
{
public static void main(String args[]) {
Box mybox1 = new Box();
double vol;
vol = mybox1.volume();
System.out.println(―Volume is ― + vol);
}
}
Parameterized constructor
Class Student
{
int id;
String name;
Student(int I,String n)
{
id = I;
name = n;
}
void display()
{
System.out.println(id+‖ ―+name);
}
}
Class test{
public static void main(String args[])
{
Student s1 = new Student(111,‖Karan‖);
Student s2 = new Student(222,‖Aryan‖);
s1.display();
s2.display();
}
}
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
Objects as Parameters
Using Objects as Parameters: So far, we have only been using simple types as parameters to
methods. However, it is both correct and common to pass objects to methods. For example,
consider the following short program
class Test {
int a, b;
Test(int i, int j) {
a = i;
b = j;
}
// return true if o is equal to the invoking
object boolean equalTo(Test o) {
if(o.a == a && o.b == b) return
true; else return false;
}
}
class PassOb {
public static void main(String args[]) {
Test ob1 = new Test(100, 22);
Test ob2 = new Test(100, 22); Test ob3 = new Test(-1, -
1); System.out.println("ob1 == ob2: " +
ob1.equalTo(ob2)); System.out.println("ob1 == ob3: " +
ob1.equalTo(ob3));
}
}
Exercise 1:
Write a java program to create 2 objects of complex numbers and pass these objects as
parameters to the methods. Perform addition of 2 complex numbers and return the sum as
an object.
Interestingly, you can have local variables, including formal parameters to methods, which
overlap with the names of the class’ instance variables. However, when a local variable has the
same name as an instance variable, the local variable hides the instance variable.
class Student
{
int rollno;
String name;
float fee;
Student(int rollno,String name,float fee)
{
this.rollno=rollno;
this.name=name;
this.fee=fee;
}
void display()
{
System.out.println(rollno+" "+name+" "+fee);
}
}
class Test
{
public static void main(String args[])
{
Student s1=new Student(111,"ankit",5000f);
Student s2=new Student(112,"sumit",6000f);
s1.display();
s2.display();
}
}
Overloaded Constructors
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter lists.The compiler differentiates these constructors by
taking into account the number of parameters in the list and their type.
class Student{
int id;
String name;
int age;
Student (int i,String n)
{
id = i;
name = n;
}
Student (int i,String n,int a)
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
{
id = i;
name = n;
age=a;
}
void display()
{
System.out.println(id+" "+name+" "+age);
}
GARBAGE COLLECTION:
In some languages, such as C++, dynamically allocated objects must be manually released by
use of a delete operator. Java takes a different approach; it handles deallocation for you
automatically. The technique that accomplishes this is called garbage collection. It works like
this: when no references to an object exist, that object is assumed to be no longer needed, and
the memory occupied by the object can be reclaimed.
Advantage of Garbage Collection
o It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
o It is automatically done by the garbage collector(a part of JVM) so we don't need to
make extra efforts.
finalize() method
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The
gc() is found in System and Runtime classes.
A Stack Class:
class Stack
{
int stck[] = new int[10];
int top;
// Initialize top-of-
stack Stack()
{
top = -1;
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
int pop()
{
if(top < 0) {
System.out.println("Stack underflow.");
return 0;
}
else
return stck[top--];
}
}
class TestStack
{
public static void main(String args[])
{
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
System.out.println("Stack in mystack1:");
for(int i=0; i<10; i++)
System.out.println(mystack1.pop());
System.out.println("Stack in mystack2:");
for(int i=0; i<10; i++)
System.out.println(mystack2.pop());
}
}
Stack in mystack1:
9
8
7
6
5
4
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
3
2
1
0
Stack in mystack2:
19
18
17
16
15
14
13
12
11
10
Overloading Methods
In Java, it is possible to define two or more methods within the same class that share
the same name, as long as their parameter declarations are different. Method overloading is
also known as Static Polymorphism.
Argument lists could differ in –
1. Number of parameters.
2. Data type of parameters.
3. Sequence of Data type of parameters.
When an overloaded method is invoked, Java uses the type and/or number of arguments
as its guide to determine which version of the overloaded method to actually call. Thus,
overloaded methods must differ in the type and/or number of their parameters. While
overloaded methods may have different return types, the return type alone is insufficient to
distinguish two versions of a method.
class Calculate
{
void sum (int a, int b)
{
System.out.println("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
System.out.println("sum is"+(a+b));
}
Public static void main (String[] args)
{
Calculate cal = new Calculate();
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
class Overloading3
{
public void disp(char c, int num)
{
System.out.println("c ");
System.out.println("num ");
}
public void disp(int num, char c)
{
System.out.println("c ");
System.out.println("num ");
}
}
class Sample3
{
public static void main(String args[])
{
Overloading3 obj = new Overloading3();
obj.disp('x', 51 );
obj.disp(52, 'y');
}
}
Recursion:
Java supports recursion. Recursion is the process of defining something in terms of itself. As
it relates to Java programming, recursion is the attribute that allows a method to call itself. A
method that calls itself is said to be recursive.
class Factorial {
int fact(int n) {
int result;
if(n==1)
return 1;
result = fact(n-1) * n;
return result;
}
}
class Recursion {
public static void main(String args[]) {
Factorial f = new Factorial();
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
Advantages of Recursion
1. Reduces time complexity.
2. Performs better in solving problems based on tree structures.
Access Control
The access modifiers in java specifies accessibility (scope) of a data member, method,
constructor or class.
There are 4 types of java access modifiers:
1. private
2. default
3. protected
4. public
public:
A class, method, constructor, interface etc declared public can be accessed from any other class.
Therefore fields, methods, blocks declared inside a public class can be accessed from any class
belonging to the Java Universe. It has the widest scope among all other modifiers.
//save by A.java
package pack;
public class A
{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B
{
public static void main(String args[]){
A obj = new A();
obj.msg();
}
}
private:
Methods, Variables and Constructors that are declared private can only be accessed within the
declared class itself. Private access modifier is the most restrictive access level. Class and
interfaces cannot be private. Variables that are declared private can be accessed outside the
class if public getter methods are present in the class.
CLASSES, INHERITANCE,EXCEPTION HANDLING BCS306A- OOP with JAVA
class A
{
private int data=40;
private void msg()
{
System.out.println("Hello java");}
}
protected:
Variables, methods and constructors which are declared protected in a superclass can be accessed
only by the subclasses in other package or any class within the package of the protected members'
class. The protected access modifier cannot be applied to class and interfaces.
//save by A.java
package pack;
public class A{
protected void msg(){System.out.println("Hello");} }
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
}
}
Default:
Default access modifier means we do not explicitly declare an access modifier for a class, field,
method, etc. A variable or method declared without any access control modifier is available to any
other class in the same package.
The fields in an interface are implicitly public static final and the methods in an interface are by
default public.
//save by A.java
package pack;
class A{
void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
}
CLASSES, INHERITANCE,EXCEPTION HANDLING
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y
Static:
It is a keyword which is used to define the class members that will be used independent
of any object of that class. Static members are initialized for the first time when class is loaded.
The most common example of a static member is main( ). main( ) is declared as static because
it must be called before any objects exist.[i.e., without instantiating the class]
Static Methods
Methods declared as static have several restrictions:
• They can only directly call other static methods.
• They can only directly access static data.
• They cannot refer to this or super in any way.
Static Blocks:
Static blocks are also called Static initialization blocks . A static initialization block is a normal
block of code enclosed in braces, { }, and preceded by the static keyword.
static {
// whatever code is needed for initialization goes here
}
class UseStatic
{
static int a = 3;
static int b;
static
{
System.out.println("Static block initialized.");
b = a * 4;
}
CLASSES, INHERITANCE,EXCEPTION HANDLING
class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme()
{
System.out.println("a = " + a);
}
}
class StaticByName
{
public static void main(String args[]) {
StaticDemo.callme();
System.out.println("b = " + StaticDemo.b);
}
}
a = 42
b = 99
Outside of the class in which they are defined, static methods and variables can be used
independently of any object. To do so, you need only specify the name of their class followed by
the dot operator.
Inheritance:
Inheritance in java is a mechanism in which one object acquires all the properties and
behaviours of parent object. The idea behind inheritance in java is that you can create new classes
that are built upon existing classes. When you inherit from an existing class, you can reuse methods
and fields of parent class, and you can add new methods and fields also.
Inheritance represents the IS-A relationship, also known as parent-child relationship. 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). extends is
the keyword used to inherit the properties of a class.
class Employee
{
float salary=40000;
}
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
class Animal
{
void eat()
{
System.out.println("eating...");
}
}
class Dog extends Animal
{
. void bark()
{
System.out.println("barking...");
}
}
class TestInheritance
{
public static void main(String args[]){
Dog d=new Dog();
d.bark();
d.eat();
}
}
barking...
eating...
CLASSES, INHERITANCE,EXCEPTION HANDLING
Multilevel Inheritance:
Multilevel inheritance refers to a mechanism in OO technology where one can inherit from a
derived class, thereby making this derived class the base class for the new class.
class Animal
{
void eat(){
System.out.println("eating...");
}
}
class Dog extends Animal
{
void bark(){
System.out.println("barking...");
}
}
class BabyDog extends Dog{
void weep()
{
System.out.println("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
d.weep();
d.bark();
d.eat();
}
}
weeping...
barking...
eating..
CLASSES, INHERITANCE,EXCEPTION HANDLING
Hierarchical Inheritance :
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//Compile Time.Error
}}
meowing...
eating...
Polymorphism:
Polymorphism in java is a concept by which we can perform a single action by different ways.
Polymorphism is derived from 2 greek words: poly and morphs. The word "poly" means many
and "morphs" means forms. So polymorphism means many forms. There are two types of
polymorphism in java:
• compile time polymorphism and
• runtime polymorphism.
Compile Time polymorphism can be achieved using overloading methods Run
Time Polymorphism can be achieved using overriding methods
Runtime Polymorphism
Runtime polymorphism or Dynamic Method Dispatch is a process in which a call to an
overridden method is resolved at runtime rather than compile-time.
Child class has the same method as of base class. In such cases child class overrides the parent
class method without even touching the source code of the base class.
class Bank{
float getRateOfInterest(){
return 0;
}
}
class SBI extends Bank{
float getRateOfInterest(){
return 8.4f;
}
}
class ICICI extends Bank{
float getRateOfInterest(){
return 7.3f;
}
}
class AXIS extends Bank{
float getRateOfInterest(){
return 9.7f;
}
}
class TestPolymorphism{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("SBI Rate of Interest: "+b.getRateOfInterest());
b=new ICICI();
System.out.println("ICICI Rate of Interest: "+b.getRateOfInterest());
b=new AXIS();
10 For overloading methods return type may or For overriding method return type should
may not be same. be same.
CLASSES, INHERITANCE,EXCEPTION HANDLING
NOTE : Static methods cannot be overridden because, a static method is bounded with class
where as instance method is bounded with object.
Super Keyword:
The super keyword in java is a reference variable which is used to refer immediate parent class
object. Whenever you create the instance of subclass, an instance of parent class is created
implicitly which is referred by super reference variable.
class Vehicle
{
int maxSpeed = 120;
}
void display()
{
System.out.println("Derived class Speed: " + maxSpeed);
System.out.println("Base Speed: " + super.maxSpeed);
}
}
CLASSES, INHERITANCE,EXCEPTION HANDLING
The super keyword can also be used to invoke or call parent class method. It should be used
in case of method overriding. In other word super keyword use when base class method name
and derived class method name have same name.
class Student
{
void message()
{
System.out.println("Good Morning Sir");
}
}
void display()
{
message(); //will invoke or call current class message() method
super.message(); //will invoke or call parent class message() method
}
• Super()
• Super(...)
Super():
Super() It is used for calling super class default constructor from the context of derived
class constructors.
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();
}
}
Employee class Constructor
HR class Constructor
Super(...)
Super(...) It is used for calling super class parameterize constructor from the context of
derived class constructor.
class Person
{
int id;
String name;
Person(int id,String name)
{
CLASSES, INHERITANCE,EXCEPTION HANDLING
this.id=id;
this.name=name;
}
}
class Emp extends Person
{
float salary;
Emp(int id,String name,float salary)
{
super(id,name); //reusing parent constructor
this.salary=salary;
}
void display()
{
System.out.println(id+" "+name+" "+salary);}
}
class TestSuper5
{
public static void main(String[] args)
{
Emp e1=new Emp(1,"abc",5000f);
e1.display();
}
}
1 abc 5000
Important rules
Rule for default constructor
Whenever the derived class constructor want to call default constructor of base class, in the
context of derived class constructors we write super(). It is optional to write because every
base class constructor contains single form of default constructor
Rule for Parameterized constructor
Whenever the derived class constructor wants to call parameterized constructor of base class
in the context of derived class constructor we must write super(...). which is mandatory to
write because a base class may contain multiple forms of parameterized constructors.
CLASSES, INHERITANCE,EXCEPTION HANDLING
Abstract Classes
An abstract class is a class that is declared abstract—It can have abstract and non-abstract
methods (method with body).Abstract classes cannot be instantiated, but they can be
subclassed.
That is we cannot create an object for abstract classes
Abstraction is a process of hiding the implementation details and showing only functionality
to the user.
Another way, it shows only important things to the user and hides the internal details for
example sending sms, you just type the text and send the message. You don't know the internal
processing about the message delivery.
• To use an abstract class, you have to inherit it from another class, provide
implementations to the abstract methods in it.
• If you inherit an abstract class, you have to provide implementations to all the
abstract methods in it.
Abstract method
Method that is declared without any body within an abstract class is called abstract method.
The method body will be defined by its subclass. Abstract method can never be final and static.
Any class that extends an abstract class must implement all the abstract methods declared by
the super class.
Syntax :
class TestAbstraction
{
public static void main(String args[])
{
Rectangle r = new Rectangle();
r.draw();
CLASSES, INHERITANCE,EXCEPTION HANDLING
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
b=new PNB();
System.out.println("Rate of Interest is: "+b.getRateOfInterest()+" %");
}
}
Rate of Interest is: 7 %
Rate of Interest is: 8 %
void changeGear(){
System.out.println("gear changed");}
}
An exception (or exceptional event) is a problem that arises during the execution of a program.
When an Exception occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not recommended, therefore, these
exceptions are to be handled.
An exception can occur for many different reasons. Following are some scenarios where an
exception occurs.
• A user has entered an invalid data.
• A file that needs to be opened cannot be found.
• A network connection has been lost in the middle of communications or the JVM
hasrun out of memory.
Some of these exceptions are caused by user error, others by programmer error, and others
by physical resources that have failed in some manner.
Errors indicate serious problems and abnormal conditions that most applications should not
try to handle. Error defines problems that are not expected to be caught under normal
circumstances by our program. For example memory error, hardware error, JVM error etc.
Exceptions are conditions within the code. A developer can handle such conditions and take
necessary corrective actions.
Few examples –
• DivideByZero exception
• NullPointerException
• ArithmeticException
• ArrayIndexOutOfBoundsException
Exception hierarchy
try-catch –
try is the start of the block and catch is at the end of try block to handle the exceptions.
We can have multiple catch blocks with a try and try-catch block can be nested also. catch
block requires a parameter that should be of type Exception.
A catch block must be associated with a try block. The corresponding catch block
executes if an exception of a particular type occurs within the try block.
CLASSES, INHERITANCE,EXCEPTION HANDLING
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
import java.io.*;
{
a=0;
b=10;
c=b/a;
System.out.println("This line will not be executed");
}
catch(ArithmeticException e)
{
System.out.println("Divided by zero");
}
System.out.println("After exception is handled");
}
}
All the statements in the catch block will be executed and then the program continues.
If the exception type of exception, matches with the first catch block it gets caught, if not the
exception is passed down to the next catch block.
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
Warning: ArithmeticException
Out of try-catch block...
Java finally block is a block that is used to execute important code such as closing connection,
stream etc.Java finally block is always executed whether exception is handled or not.
Finally block is optional and can be used only with try-catch block. Since exception halts
the process of execution, we might have some resources open that will not get closed, so we
can use finally block. finally block gets executed always, whether exception occurred or not
class TestFinallyBlock1{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e)
{
System.out.println(e);
}
finally
{
System.out.println("finally block is always executed");
}
System.out.println("rest of the code...");
}
}
Output:finally block is always executed
Exception in thread main java.lang.ArithmeticException:/ by zero
Exception Handling is mainly used to handle the checked exceptions. If there occurs
any unchecked exception such as NullPointerException, it is programmers fault that he is not
performing check up before the code being used.
throws – When we are throwing any exception in a method and not handling it, then we need
to use throws keyword in method signature to let caller program know the exceptions that
might be thrown by the method. The caller method might handle these exceptions or propagate
it to its caller method using throws keyword. We can provide multiple exceptions in the throws
clause and it can be used with main() method also.
throw –
CLASSES, INHERITANCE,EXCEPTION HANDLING
We know that if any exception occurs, an exception object is getting created and then
Java runtime starts processing to handle them. Sometime we might want to generate exception
explicitly in our code, for example in a user authentication program we should throw exception
to client if the password is null. throw keyword is used to throw exception to the runtime to
handle it.
import java.io.*;
class M
{
void method()throws IOException
{
throw new IOException("device error");
}
}
class Testthrows4
{
public static void main(String args[]) throws IOException
{
M m=new M();
m.method();
System.out.println("normal flow...");
}
}
Exception in thread "main" java.io.IOException: device error
Final methods:
While method overriding is one of Java’s most powerful features, there will be times when you
will want to prevent it from occurring. To disallow a method from being overridden, specify
final as a modifier at the start of its declaration. Methods declared as final cannot be overridden.
class Bike
{
final void run()
{
System.out.println("running");
}
}
honda.run();
}
}
Complie Time Error as Final methods cannot be overridden
Final Class:
Sometimes you will want to prevent a class from being inherited. To do this, precede the class
declaration with final. Declaring a class as final implicitly declares all of its methods as final, too.
As you might expect, it is illegal to declare a class as both abstract and final since an abstract class
is incomplete by itself and relies upon its subclasses to provide complete implementations.
Here is an example of a final class:
Final variable
If you make any variable as final, you cannot change the value of final
variable (It will be constant).
class Bike
{
final int speedlimit=90; //final variable
void run()
{
speedlimit=400;
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run(); //Compile Time Error
}
}
Compile Time Error