Module 3 -Java
Classes & Objects
Class Fundamentals:
A class is declared by using class keyword. class is a template for an object, and an object is
an instance of a class.
Syntax :
class classname {
type instance-variable1;
type instance-variable2;
// ...
type instance-variableN;
type methodname1(parameter-list) {
// body of method
}
type methodname2(parameter-list) {
// body of method
}
// ...
type methodnameN(parameter-list) {
// body of method
}
}
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.
Declaring Objects/ Instantiating a Class:
Creating objects of a class is a two-step process.
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.
Box mybox = new Box();
OR
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Mrs Srivani P BMSIT&M Page 1
Module 3 -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.
Java Heap Space
Java Heap space is used by java runtime to allocate memory to Objects and JRE classes.
Whenever we create any object, it’s always created in the Heap space. Garbage Collection runs
on the heap memory to free the memory used by objects that doesn’t have any reference.
Java Stack Memory
Java Stack memory is used for execution of a thread. They contain method specific values that
are short-lived and references to other objects in the heap that are getting referred from the
method. Stack memory is always referenced in LIFO (Last-In-First-Out) order
Mrs Srivani P BMSIT&M Page 2
Module 3 -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;
[Link] = 10;
[Link] = 20;
[Link] = 15;
vol = [Link] * [Link] * [Link];
[Link](“Volume is “ + vol);
}
}
Introducing Methods
This is the general form of a method:
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;
}
void setDim(double w, double h, double d) {
width = w;
height = h;
depth = d;
Mrs Srivani P BMSIT&M Page 3
Module 3 -Java
}
}
class Demo {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
[Link](10, 20, 15);
[Link](3, 6, 9);
vol = [Link]();
[Link](“Volume is “ + vol);
vol = [Link]();
[Link](“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
[Link] name of the constructor must be the same as the name of the [Link] methods,
constructors are not considered members of a class.
A constructor is called automatically when a new instance of an object is created.
There are two types of constructors:
1. Default constructor (no-arg constructor)
2. Parameterized constructor
Default Constructor: It is a constructor which do not take any [Link] 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()
{
[Link](“Constructing Box”);
width = 10;
height = 10;
depth = 10;
}
Mrs Srivani P BMSIT&M Page 4
Module 3 -Java
double volume() {
return width * height * depth;
}
}
class demo
{
public static void main(String args[]) {
Box mybox1 = new Box();
double vol;
vol = [Link]();
[Link](“Volume is “ + vol);
}
}
Parameterized constructor
A constructor that have parameters is known as parameterized constructor.
Class Student
{
int id;
String name;
Student(int I,String n)
{
id = I;
name = n;
}
void display()
{
[Link](id+” “+name);
}
}
Class test{
public static void main(String args[])
{
Student s1 = new Student(111,”Karan”);
Student s2 = new Student(222,”Aryan”);
[Link]();
[Link]();
}
}
Mrs Srivani P BMSIT&M Page 5
Module 3 -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);
[Link]("ob1 == ob2: " + [Link](ob2));
[Link]("ob1 == ob3: " + [Link](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.
The this Keyword
Java defines the this keyword. It can be used inside any method to refer to the current object.
Box(double w, double h, double d)
{
[Link] = w;
[Link] = h;
[Link] = d;
}
this keyword is used to refer to current object.
this is always a reference to the object on which method was invoked.
this can be used to invoke current class constructor.
this can be passed as an argument to another method.
Mrs Srivani P BMSIT&M Page 6
Module 3 -Java
Instance Variable Hiding:
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)
{
[Link]=rollno;
[Link]=name;
[Link]=fee;
}
void display()
{
[Link](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);
[Link]();
[Link]();
}
}
Overloaded Constructors
Constructor overloading is a technique in Java in which a class can have any number of
constructors that differ in parameter [Link] 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)
Mrs Srivani P BMSIT&M Page 7
Module 3 -Java
{
id = i;
name = n;
age=a;
}
void display()
{
[Link](id+" "+name+" "+age);
}
public static void main(String args[])
{
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
[Link]();
[Link]();
}
}
Role of this () in constructor overloading
/*this() is used for calling the default constructor from parameterized constructor. It should
always be the first statement in constructor body. */
public class student
{
private int rollNum;
student()
{
rollNum =100;
}
student(int rnum)
{
this();
rollNum = rollNum+ rnum;
}
public int getRollNum() {
return rollNum;
}
public void setRollNum(int rollNum) {
[Link] = rollNum;
}
}
class TestDemo{
public static void main(String args[])
{
student obj = new student(12);
[Link]([Link]());
}
}
Mrs Srivani P BMSIT&M Page 8
Module 3 -Java
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:
protected void finalize()
{
//code
}
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.
1. public class TestGarbage1{
2. public void finalize(){[Link]("object is garbage collected");}
3. public static void main(String args[]){
4. TestGarbage1 s1=new TestGarbage1();
5. TestGarbage1 s2=new TestGarbage1();
6. s1=null;
7. s2=null;
8. [Link]();
9. }
}
object is garbage collected
object is garbage collected
A Stack Class:
class Stack
{
int stck[] = new int[10];
int top;
// Initialize top-of-stack
Stack()
{
top = -1;
Mrs Srivani P BMSIT&M Page 9
Module 3 -Java
void push(int item)
{
if(top==9)
[Link]("Stack is full.");
else
stck[++top] = item;
}
int pop()
{
if(top < 0) {
[Link]("Stack underflow.");
return 0;
}
else
return stck[top--];
}
}
class TestStack
{
public static void main(String args[])
{
Stack mystack1 = new Stack();
Stack mystack2 = new Stack();
// push some numbers onto the stack
for(int i=0; i<10; i++)
[Link](i);
for(int i=10; i<20; i++)
[Link](i);
[Link]("Stack in mystack1:");
for(int i=0; i<10; i++)
[Link]([Link]());
[Link]("Stack in mystack2:");
for(int i=0; i<10; i++)
[Link]([Link]());
}
}
Stack in mystack1:
9
8
7
6
5
4
Mrs Srivani P BMSIT&M Page 10
Module 3 -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.
Advantage of method overloading
1) Method overloading increases the readability of the program.
class Calculate
{
void sum (int a, int b)
{
[Link]("sum is"+(a+b)) ;
}
void sum (float a, float b)
{
[Link]("sum is"+(a+b));
}
Public static void main (String[] args)
{
Calculate cal = new Calculate();
[Link] (8,5); //sum(int a, int b) is method is called.
Mrs Srivani P BMSIT&M Page 11
Module 3 -Java
[Link] (4.6f, 3.8f); //sum(float a, float b) is called.
}
}
Sum is 13
Sum is 8.4
class Overloading3
{
public void disp(char c, int num)
{
[Link]("c ");
[Link]("num ");
}
public void disp(int num, char c)
{
[Link]("c ");
[Link]("num ");
}
}
class Sample3
{
public static void main(String args[])
{
Overloading3 obj = new Overloading3();
[Link]('x', 51 );
[Link](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();
Mrs Srivani P BMSIT&M Page 12
Module 3 -Java
[Link]("Factorial of 3 is " + [Link](3));
[Link]("Factorial of 4 is " + [Link](4));
[Link]("Factorial of 5 is " + [Link](5));
}
}
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 [Link]
package pack;
public class A
{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B
{
public static void main(String args[]){
A obj = new A();
[Link]();
}
}
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.
Mrs Srivani P BMSIT&M Page 13
Module 3 -Java
1. class A
2. {
3. private int data=40;
4. private void msg()
5. {
6. [Link]("Hello java");}
7. }
8.
9. public class Simple
10. {
11. public static void main(String args[])
{
A obj=new A();
[Link]([Link]); //Compile Time Error
[Link](); //Compile Time Error
}
}
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.
1. //save by [Link]
2. package pack;
3. public class A{
4. protected void msg(){[Link]("Hello");}
5. }
1. //save by [Link]
2. package mypack;
3. import pack.*;
4.
5. class B extends A{
6. public static void main(String args[]){
7. B obj = new B();
8. [Link]();
9. }
}
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.
Mrs Srivani P BMSIT&M Page 14
Module 3 -Java
The fields in an interface are implicitly public static final and the methods in an interface are
by default public.
1. //save by [Link]
2. package pack;
3. class A{
4. void msg(){[Link]("Hello");}
5. }
1. //save by [Link]
2. package mypack;
3. import pack.*;
4. class B{
5. public static void main(String args[]){
6. A obj = new A();//Compile Time Error
7. [Link]();//Compile Time Error
8. }
9. }
Access within class within outside package by outside package
Modifier package subclass only
Private Y N N N
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 {
Mrs Srivani P BMSIT&M Page 15
Module 3 -Java
// whatever code is needed for initialization goes here
}
class UseStatic
{
static int a = 3;
static int b;
static void display (int x)
{
[Link]("x = " + x);
[Link]("a = " + a);
[Link]("b = " + b);
}
static
{
[Link]("Static block initialized.");
b = a * 4;
}
public static void main(String args[])
{
display (42);
}
}
Static block initialized.
x = 42
a=3
b = 12
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.
class StaticDemo
{
static int a = 42;
static int b = 99;
static void callme()
{
[Link]("a = " + a);
}
}
class StaticByName
{
public static void main(String args[]) {
[Link]();
Mrs Srivani P BMSIT&M Page 16
Module 3 -Java
[Link]("b = " + StaticDemo.b);
}
}
a = 42
b = 99
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.
Use of inheritance in java
o For Method Overriding (so runtime polymorphism can be achieved).
o For Code Reusability.
Syntax of Java Inheritance
class Subclass-name extends Superclass-name
{
//methods and fields
}
1. class Employee
2. {
3. float salary=40000;
4. }
5.
Mrs Srivani P BMSIT&M Page 17
Module 3 -Java
6. class Programmer extends Employee
7. {
8. int bonus=10000;
9. public static void main(String args[])
{
Programmer p=new Programmer();
[Link]("Programmer salary is:"+[Link]);
[Link]("Bonus of Programmer is:"+[Link]);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000
Types of Inheritance
1. Single Inheritance
2. Multilevel Inheritance
3. Hierarchical Inheritance
Single Level Inheritance :
One class extends one class only
1. class Animal
2. {
3. void eat()
4. {
5. [Link]("eating...");
6. }
7. }
8. class Dog extends Animal
9. {
10. void bark()
{
[Link]("barking...");
}
}
class TestInheritance
{
Mrs Srivani P BMSIT&M Page 18
Module 3 -Java
public static void main(String args[]){
Dog d=new Dog();
[Link]();
[Link]();
}
}
barking...
eating...
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(){
[Link]("eating...");
}
}
class Dog extends Animal
{
void bark(){
[Link]("barking...");
}
}
class BabyDog extends Dog{
void weep()
{
[Link]("weeping...");
}
}
class TestInheritance2
{
public static void main(String args[])
{
BabyDog d=new BabyDog();
[Link]();
[Link]();
[Link]();
}
}
weeping...
barking...
eating..
Mrs Srivani P BMSIT&M Page 19
Module 3 -Java
Hierarchical Inheritance :
In simple terms you can say that Hybrid inheritance is a combination
of Single and Multiple inheritance. In Hierarchical inheritance one parent class will be
inherited by many sub classes.
class Animal{
void eat(){[Link]("eating...");}
}
class Dog extends Animal{
void bark(){[Link]("barking...");}
}
class Cat extends Animal{
void meow(){[Link]("meowing...");}
}
class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
[Link]();
[Link]();
//[Link]();//Compile [Link]
}}
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.
Advantage of Java Method Overriding
Method Overriding is used to provide specific implementation of a method that is
already provided by its super class.
Method Overriding is used for Runtime Polymorphism
Mrs Srivani P BMSIT&M Page 20
Module 3 -Java
Rules for Method Overriding
method must have same name as in the parent class.
method must have same parameter as in the parent class.
must be IS-A relationship (inheritance).
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();
[Link]("SBI Rate of Interest: "+[Link]());
b=new ICICI();
[Link]("ICICI Rate of Interest: "+[Link]());
b=new AXIS();
[Link]("AXIS Rate of Interest: "+[Link]());
}
}
SBI Rate of Interest: 8.4
Mrs Srivani P BMSIT&M Page 21
Module 3 -Java
ICICI Rate of Interest: 7.3
AXIS Rate of Interest: 9.7
Difference between Overloading and Overriding
Overloading Overriding
Whenever same method or Constructor is Whenever same method name is existing
existing multiple times within a class either multiple time in both base and derived
1 with different number of parameter or with class with same number of parameter or
different type of parameter or with different same type of parameter or same order of
order of parameter is known as Overloading. parameters is known as Overriding.
Arguments of method must be different at Argument of method must be same
2
least arguments. including order.
3 Method signature must be different. Method signature must be same.
Private, static and final methods can be Private, static and final methods can not be
4
overloaded. override.
Access modifiers point of view not reduced
5 Access modifiers point of view no restriction.
scope of Access modifiers but increased.
Also known as compile time polymorphism or Also known as run time polymorphism or
6
static polymorphism or early binding. dynamic polymorphism or late binding.
Overloading can be exhibited both are method Overriding can be exhibited only at method
7
and constructor level. label.
The scope of Overriding is base class and
8 The scope of overloading is within the class.
derived class.
Overloading can be done at both static and Overriding can be done only at non-static
9
non-static methods. method.
For overloading methods return type may or For overriding method return type should
10
may not be same. be same.
Mrs Srivani P BMSIT&M Page 22
Module 3 -Java
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.
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.
1) super is used to refer immediate parent class instance variable.
This scenario occurs when a derived class and base class has same data members. Hence we
use super keyword to refer a member of immediate parent class.
class Vehicle
{
int maxSpeed = 120;
}
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
[Link]("Derived class Speed: " + maxSpeed);
[Link]("Base Speed: " + [Link]);
}
}
Mrs Srivani P BMSIT&M Page 23
Module 3 -Java
/* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
[Link]();
}
}
Derived class Speed: 180
Base class Speed: 120
2) super can be used to invoke parent class method
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()
{
[Link]("Good Morning Sir");
}
}
class Faculty extends Student
{
void message()
{
[Link]("Good Morning Students");
}
void display()
{
message(); //will invoke or call current class message() method
[Link](); //will invoke or call parent class message() method
}
public static void main(String args[])
{
Student s=new Student();
[Link]();
}
}
Good Morning Students
Good Morning Sir
Mrs Srivani P BMSIT&M Page 24
Module 3 -Java
3) super is used to invoke parent class constructor.
The super keyword can also be used to invoke or call the parent class constructor.
Constructor are calling from bottom to top and executing from top to bottom.
To establish the connection between base class constructor and derived class constructors
JVM provides two implicit methods they are: If super is not used explicitly compiler will
automatically add super as the first statement.
Super()
Super(...)
Super():
Super() It is used for calling super class default constructor from the context of derived
class constructors.
class Employee
{
Employee()
{
[Link]("Employee class Constructor");
}
}
class HR extends Employee
{
HR()
{
super(); //will invoke or call parent class constructor
[Link]("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;
Mrs Srivani P BMSIT&M Page 25
Module 3 -Java
Person(int id,String name)
{
[Link]=id;
[Link]=name;
}
}
class Emp extends Person
{
float salary;
Emp(int id,String name,float salary)
{
super(id,name); //reusing parent constructor
[Link]=salary;
}
void display()
{
[Link](id+" "+name+" "+salary);}
}
class TestSuper5
{
public static void main(String[] args)
{
Emp e1=new Emp(1,"abc",5000f);
[Link]();
}
}
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.
Mrs Srivani P BMSIT&M Page 26
Module 3 -Java
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 :
abstract return_type function_name ();
abstract class Shape
{
abstract void draw();
}
class Rectangle extends Shape{
void draw(){
[Link]("drawing rectangle");}
}
class Circle extends Shape{
void draw(){
[Link]("drawing circle");}
}
class TestAbstraction
{
public static void main(String args[])
{
Rectangle r = new Rectangle();
[Link]();
Mrs Srivani P BMSIT&M Page 27
Module 3 -Java
Shape s=new Circle();
[Link]();
}
}
drawing rectangle
drawing circle
abstract class Bank{
abstract int getRateOfInterest();
}
class SBI extends Bank{
int getRateOfInterest(){return 7;}
}
class PNB extends Bank{
int getRateOfInterest(){return 8;}
}
class TestBank{
public static void main(String args[]){
Bank b;
b=new SBI();
[Link]("Rate of Interest is: "+[Link]()+" %");
b=new PNB();
[Link]("Rate of Interest is: "+[Link]()+" %");
}
}
Rate of Interest is: 7 %
Rate of Interest is: 8 %
Abstract classes with constructors
abstract class Bike
{
Bike(){
[Link]("bike is created");
}
abstract void run();
void changeGear(){
[Link]("gear changed");}
}
class Honda extends Bike{
void run(){
[Link]("running safely..");
}
}
class TestAbstraction2{
public static void main(String args[]){
Mrs Srivani P BMSIT&M Page 28
Module 3 -Java
Bike obj = new Honda();
[Link]();
[Link]();
}
}
bike is created
running safely..
gear changed
When to use Abstract Methods & Abstract Class?
Abstract methods are usually declared where two or more subclasses are expected to
do a similar thing in different ways through different implementations. These subclasses extend
the same Abstract class and provide different implementations for the abstract methods.
Abstract classes are used to define generic types of behaviours at the top of an object-oriented
programming class hierarchy, and use its subclasses to provide implementation details of the
abstract class.
Packages:
Packages in Java is a mechanism to encapsulate a group of classes, interfaces and sub
[Link] create a package is quite easy: simply include a package command as the first
statement in a Java source file. Any classes declared within that file will belong to the specified
package. The package statement defines a name space in which classes are stored. If you omit
the package statement, the class names are put into the default package, which has no name.
This is the general form of the package statement:
package pkg;
Java uses file system directories to store packages. For example, the .class files for any classes
you declare to be part of MyPackage must be stored in a directory called MyPackage.
You can create a hierarchy of packages.
package pkg1[.pkg2[.pkg3]];
Ex: package [Link];
Advantages of using a package
Reusability: Reusability of code is one of the most important requirements in the
software industry. Reusability saves time, effort and also ensures consistency. A class
once developed can be reused by any number of programs wishing to incorporate the
class in that particular program.
Easy to locate the files.
In real life situation there may arise scenarios where we need to define files of the same
name. This may lead to “name-space collisions”. Packages are a way of avoiding “name-
space collisions”.
Package are categorized into two forms
Built-in Package:-Existing Java package for example [Link], [Link] etc.
User-defined-package:- Java package created by user to categorized classes and interface
Mrs Srivani P BMSIT&M Page 29
Module 3 -Java
How to compile & Run java package?
If you are not using any IDE, you need to follow this:
Compile :- javac -d . [Link]
Run :- java [Link]
How to access package from another package?
There are three ways to access the package from outside the package.
1. import package.*;
2. import [Link];
3. fully qualified name.
1) Using packagename.*
If you use package.* then all the classes and interfaces of this package will be accessible but
not sub packages. The import keyword is used to make the classes and interface of another
package accessible to the current package.
//save by [Link]
package pack;
public class A{
public void msg(){[Link]("Hello");}
}
//save by [Link]
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
[Link]();
}
Mrs Srivani P BMSIT&M Page 30
Module 3 -Java
2) Using [Link]
If you import [Link] then only declared class of this package will be accessible.
1. //save by [Link]
2.
3. package pack;
4. public class A{
5. public void msg(){[Link]("Hello");}
6. }
1. //save by [Link]
2. package mypack;
3. import pack.A;
4.
5. class B{
6. public static void main(String args[]){
7. A obj = new A();
8. [Link]();
9. }
}
3) Using fully qualified name
If you use fully qualified name then only declared class of this package will be accessible. Now
there is no need to import. But you need to use fully qualified name every time when you are
accessing the class or interface.
1. //save by [Link]
2. package pack;
3. public class A{
4. public void msg(){[Link]("Hello");}
5. }
1. //save by [Link]
2. package mypack;
3. class B{
4. public static void main(String args[]){
5. pack.A obj = new pack.A();//using fully qualified name
6. [Link]();
7. }
8. }
Access Specifiers
private: accessible only in the class
default : so-called “package” access — accessible only in the same package
protected: accessible (inherited) by subclasses, and accessible by code in same package
public: accessible anywhere the class is accessible, and inherited by subclasses
Mrs Srivani P BMSIT&M Page 31
Module 3 -Java
Notice that private protected is not syntactically legal.
Exception Handling in Java
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 has
run 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.
Difference between error and exception
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
Advantages of Exception Handling
Exception handling allows us to control the normal flow of the program by using
exception handling in program.
It throws an exception whenever a calling method encounters an error providing that
the calling method takes care of that error.
Mrs Srivani P BMSIT&M Page 32
Module 3 -Java
It also gives us the scope of organizing and differentiating between different error types
using a separate block of codes. This is done with the help of try-catch blocks.
Exception hierarchy
In Java, there are two types of exceptions:
1) Checked: are the exceptions that are checked at compile time. If some code within a method
throws a checked exception, then the method must either handle the exception or it must specify
the exception using throws keyword.
Example, consider the following Java program that opens file at location “C:\test\[Link]” and
prints the first three lines of it. The program doesn’t compile, because the function main() uses
FileReader() and FileReader() throws a checked exception FileNotFoundException. It also
uses readLine() and close() methods, and these methods also throw checked exception
IOException
2) Unchecked are the exceptions that are not checked at compiled time. In C++, all exceptions
are unchecked, so it is not forced by the compiler to either handle or specify the exception. It
is up to the programmers to be civilized, and specify or catch the exceptions.
Mrs Srivani P BMSIT&M Page 33
Module 3 -Java
In Java exceptions under Error and RuntimeException classes are unchecked exceptions,
everything else under throwable is checked.
Java Exception Handling Keywords
Java provides specific keywords for exception handling purposes,
1. try
2. catch
3. finally
4. throw
5. throws
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.
For example if an arithmetic exception occurs in try block then the statements enclosed
in catch block for arithmetic exception executes.
Syntax of try catch in java
try
{
//statements that may cause an exception
}
catch (exception(type) e(object))
{
//error handling code
}
import [Link].*;
public class ExcepTest
{
public static void main(String args[])
{
try {
int a[] = new int[2];
[Link]("Access element three :" + a[3]);
}
catch(ArrayIndexOutOfBoundsException e)
{
[Link]("Exception thrown :" + e);
}
[Link]("Out of the block");
}
}
Mrs Srivani P BMSIT&M Page 34
Module 3 -Java
class Excp
{
public static void main(String args[])
{
int a,b,c;
try
{
a=0;
b=10;
c=b/a;
[Link]("This line will not be executed");
}
catch(ArithmeticException e)
{
[Link]("Divided by zero");
}
[Link]("After exception is handled");
}
}
Multiple Catch Blocks
A try block can be followed by multiple catch blocks.
If the try block throws an exception, the appropriate catch block (if one exists) will catch it
–catch(ArithmeticException e) is a catch block that can catch ArithmeticException
–catch(NullPointerException e) is a catch block that can catch NullPointerException
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;
[Link]("First print statement in try block");
}
catch(ArithmeticException e){
[Link]("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
[Link]("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
[Link]("Warning: Some Other exception");
}
[Link]("Out of try-catch block...");
}
}
Mrs Srivani P BMSIT&M Page 35
Module 3 -Java
Warning: ArithmeticException
Out of try-catch block...
Java finally block
Java finally block is a block that is used to execute important code such as closing connection,
stream [Link] 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
1. class TestFinallyBlock1{
2. public static void main(String args[]){
3. try{
4. int data=25/0;
5. [Link](data);
6. }
7. catch(NullPointerException e)
8. {
9. [Link](e);
}
finally
{
[Link]("finally block is always executed");
}
[Link]("rest of the code...");
}
}
Output:finally block is always executed
Exception in thread main [Link]:/ by zero
Java throws keyword
The Java throws keyword is used to declare an exception. It gives an information to
the programmer that there may occur an exception so it is better for the programmer to provide
the exception handling code so that normal flow can be maintained.
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
Mrs Srivani P BMSIT&M Page 36
Module 3 -Java
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.
Syntax of java throws
return_type method_name() throws exception_class_name
{
//method code
}
throw –
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.
Throw instance();
where,
instance is of object type of an exception.
Example:
throw new ArithmeticException("/ by zero");
import [Link].*;
class Test
{
static void check() throws ArithmeticException
{
[Link]("Inside check function");
throw new ArithmeticException ("demo Exception ");
}
public static void main(String args[])
{
try
{
check();
}
catch(ArithmeticException e)
{
[Link]("caught in main\n" + e);
}
}
}
Output:Inside check function
caught in main
Mrs Srivani P BMSIT&M Page 37
Module 3 -Java
[Link]: demo Exception
What is the difference between throw and throws?
throw throws
It is used to create a new Exception It is used in method definition, to
object and throw it declare that a risky method is being
called.
Using throw keyword you can declare Using throws keyword you can declare
only one Exception at a time multiple exception at a time.
Example: Example:
throw new IOException("can not open throws IOException,
connection"); ArrayIndexBoundException;
USER_DEFINED EXCEPTION HANDLING- throw & throws
import [Link].*;
class InsufficientFundsException extends Exception
{
private double amount;
public InsufficientFundsException(double amount)
{
[Link] = amount;
}
public double getAmount()
{
return amount;
}
}
public class Main
{
private double balance;
private int number;
public Main(int balance)
{
[Link] = balance;
}
Mrs Srivani P BMSIT&M Page 38
Module 3 -Java
public void withdraw(double amount) throws InsufficientFundsException
{
if(amount <= balance)
{
balance -= amount;
}
else
{
double needs = amount - balance;
throw new InsufficientFundsException(needs);
}
}
public static void main(String[] args) {
[Link]("Hello World");
Main c= new Main(1000);
try {
[Link](2000);
} catch(InsufficientFundsException e) {
[Link]("Sorry, but you are short $"
+ [Link]());
[Link]();
} finally {
}
}
}
Output:
Hello World
Sorry, but you are short $1000.0
InsufficientFundsException
at [Link]([Link])
Interfaces:
An interface in java is a blueprint of a class. It has static constants and abstract [Link]
interface in java is a mechanism to achieve abstraction. There can be only abstract methods
in the java interface not method body. It is used to achieve abstraction and multiple inheritance
in Java.
Java Interface also represents IS-A [Link] cannot be instantiated just like abstract
class.
There are mainly three reasons to use interface. They are given below.
o It is used to achieve abstraction.
o By interface, we can support the functionality of multiple inheritance.
o It can be used to achieve loose coupling.
Mrs Srivani P BMSIT&M Page 39
Module 3 -Java
Implementing Interfaces
A class uses the implements keyword to implement an interface.
Syntax:
access_modifier interface nameofinterface
{
Function prototype1;
Function Prototype 2;
Type static final variable= value;
}
Rules for using Interface
Methods inside Interface must not be static, final.
All variables declared inside interface are implicitly public static final
variables(constants).
All methods declared inside Java Interfaces are implicitly public and abstract, even if you
don't use public or abstract keyword.
Interface can extend one or more other interface.
Interface cannot implement a class.
Interface can be nested inside another interface.
Interface cannot be declared as private, protected.
Variables declared in interface are public, static and final by default.
1. interface Bank
2. {
3. float rateOfInterest();
4. }
5.
6. class SBI implements Bank
7. {
8. public float rateOfInterest()
9. {
10. return 9.15f;
}
}
class PNB implements Bank
{
public float rateOfInterest()
{
return 9.7f;
}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
[Link]("ROI: "+[Link]());
}
Mrs Srivani P BMSIT&M Page 40
Module 3 -Java
abstract Classes Interfaces
1 abstract class can extend only one class or one interface can extend any number of
abstract class at a time interfaces at a time
2 abstract class can extend from a class or from an interface can extend only from an
abstract class interface
3 abstract class can have both abstract and interface can have only abstract methods
concrete methods
4 A class can extend only one abstract class A class can implement any number of
interfaces
5 In abstract class keyword ‘abstract’ is mandatory In an interface keyword ‘abstract’ is
to declare a method as an abstract optional to declare a method as an abstract
6 abstract class can have protected , public and Interface can have only public abstract
public abstract methods methods i.e. by default
7 abstract class can have static, final or static interface can have only static final
final variable with any access specifier (constant) variable i.e. by default
abstract class Shape {
abstract double area();
}
public interface Drawable {
public abstract void draw();
public class Circle extends Shape implements Drawable {
double radius;
Circle(double aRadius){
radius= aRadius;
}
double area(){
Mrs Srivani P BMSIT&M Page 41
Module 3 -Java
return [Link]*radius*radius;
}
public void draw(){
[Link]("This is a circle");
}
}
Class test
{
Public static void main(String args[])
{
Shape obj= new Rectangle();
Shape obj1= new Circle();
[Link]();
[Link]();
}
}
The relationship between classes and interfaces
As shown in the figure given below, a class extends another class, an interface extends
another interface, but a class implements an interface.
Example: interface Bank{
float rateOfInterest();
}
class SBI implements Bank
{
public float rateOfInterest(){return 9.15f;}
}
class PNB implements Bank{
Mrs Srivani P BMSIT&M Page 42
Module 3 -Java
public float rateOfInterest(){return 9.7f;}
}
class TestInterface2{
public static void main(String[] args){
Bank b=new SBI();
[Link]("ROI: "+[Link]());
}
}
Output: ROI: 9.15
Multiple inheritance in Java by interface
If a class implements multiple interfaces, or an interface extends multiple interfaces, it is
known as multiple inheritance.
1. interface Printable{
2. void print();
3. }
4. interface Showable{
5. void show();
6. }
7. class Test implements Printable,Showable{
8. public void print(){
9. [Link]("Hello");}
public void show(){
[Link]("Welcome");}
public static void main(String args[]){
Test obj = new Test ();
[Link]();
[Link]();
Mrs Srivani P BMSIT&M Page 43
Module 3 -Java
}
}
Output:Hello
Welcome
Interface and Inheritance
An interface cannot implement another interface. It has to extend the other interface. See the
below example where we have two interfaces Inf1 and Inf2. Inf2 extends Inf1 so If class
implements the Inf2 it has to provide mplementation of all the methods of interfaces Inf2 as
well as Inf1.
interface Inf1{
public void method1();
}
interface Inf2 extends Inf1 {
public void method2();
}
public class Demo implements Inf2{
/* Even though this class is only implementing the
* interface Inf2, it has to implement all the methods
* of Inf1 as well because the interface Inf2 extends Inf1
*/
public void method1(){
[Link]("method1");
}
public void method2(){
[Link]("method2");
}
public static void main(String args[]){
Inf2 obj = new Demo();
obj.method2();
}
}
Final Class, Final methods & Final variables:
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.
The following fragment illustrates final:
Mrs Srivani P BMSIT&M Page 44
Module 3 -Java
class Bike
{
final void run()
{
[Link]("running");
}
}
class Honda extends Bike
{
void run()
{
[Link]("running safely with 100kmph");
}
public static void main(String args[]){
Honda honda= new Honda();
[Link]();
}
}
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:
1. final class Bike{}
2.
3. class Honda1 extends Bike{
4. void run(){[Link]("running safely with 100kmph");}
5.
6. public static void main(String args[]){
7. Honda1 honda= new Honda();
8. [Link]();
9. }
}
Output:Compile Time Error
Final variable
If you make any variable as final, you cannot change the value of final variable
(It will be constant).
1. class Bike
2. {
3. final int speedlimit=90; //final variable
Mrs Srivani P BMSIT&M Page 45
Module 3 -Java
4. void run()
5. {
6. speedlimit=400;
7. }
8. public static void main(String args[]){
9. Bike9 obj=new Bike9();
[Link](); //Compile Time Error
}
}
Compile Time Error
Mrs Srivani P BMSIT&M Page 46