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

Unit 2

The document explains the concepts of classes and objects in Java, defining an object as an entity with state, behavior, and identity, and a class as a blueprint for creating objects. It covers the characteristics of objects, methods, constructors, and different ways to initialize objects, along with examples demonstrating these concepts. Additionally, it discusses method overloading and its advantages in enhancing code readability.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Unit 2

The document explains the concepts of classes and objects in Java, defining an object as an entity with state, behavior, and identity, and a class as a blueprint for creating objects. It covers the characteristics of objects, methods, constructors, and different ways to initialize objects, along with examples demonstrating these concepts. Additionally, it discusses method overloading and its advantages in enhancing code readability.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 29

1

Class and Objects -

What is an object in Java

An entity that has state and behaviour is known as an object e.g., chair, bike, marker, pen,
table, car, etc. It can be physical or logical (tangible and intangible). The example of an
intangible object is the banking system.

An object has three characteristics:

 State: represents the data (value) of an object.


 Behaviour: represents the behaviour (functionality) of an object such as deposit,
withdraw, etc.
 Identity: An object identity is typically implemented via a unique ID. The value of
the ID is not visible to the external user. However, it is used internally by the JVM to
identify each object uniquely.

Amit Srivastava (M.Tech. MNNIT)


2

For Example, Pen is an object. Its name is Reynolds; color is white, known as its state. It is
used to write, so writing is its behavior.

An object is an instance of a class. A class is a template or blueprint from which objects are
created. So, an object is the instance(result) of a class.

Object Definitions:

 An object is a real-world entity.


 An object is a runtime entity.
 The object is an entity which has state and behavior.
 The object is an instance of a class.

What is a class in Java


A class is a group of objects which have common properties. It is a template or blueprint
from which objects are created. It is a logical entity. It can't be physical.

A class in Java can contain:

 Fields
 Methods
 Constructors
 Blocks
 Nested class and interface

Amit Srivastava (M.Tech. MNNIT)


3

Syntax to declare a class:

class <class_name>{
field;
method;
}

Instance variable in Java

A variable which is created inside the class but outside the method is known as an instance
variable. Instance variable doesn't get memory at compile time. It gets memory at runtime
when an object or instance is created. That is why it is known as an instance variable.

Method in Java

In Java, a method is like a function which is used to expose the behaviour of an object.

Advantage of Method

 Code Reusability
 Code Optimization

new keyword in Java

The new keyword is used to allocate memory at runtime. All objects get memory in Heap
memory area.

Object and Class Example: main within the class

In this example, we have created a Student class which has two data members id and name.
We are creating the object of the Student class by new keyword and printing the object's
value.

Here, we are creating a main() method inside the class.

File: Student.java

//Java Program to illustrate how to define a class and fields


//Defining a Student class.
class Student{
//defining fields
int id;//field or data member or instance variable
String name;
//creating main method inside the Student class
public static void main(String args[]){
Amit Srivastava (M.Tech. MNNIT)
4

//Creating an object or instance


Student s1=new Student();//creating an object of Student
//Printing values of the object
System.out.println(s1.id);//accessing member through reference variable
System.out.println(s1.name);
}
}

Object and Class Example: main outside the class

In real time development, we create classes and use it from another class. It is a better
approach than previous one. Let's see a simple example, where we are having main() method
in another class.

We can have multiple classes in different Java files or single Java file. If you define multiple
classes in a single Java source file, it is a good idea to save the file name with the class name
which has main() method.

File: TestStudent1.java

//Java Program to demonstrate having the main method in


//another class
//Creating Student class.
class Student{
int id;
String name;
}
//Creating another class TestStudent1 which contains the main method
class TestStudent1{
public static void main(String args[]){
Student s1=new Student();
System.out.println(s1.id);
System.out.println(s1.name);
}
}

3 Ways to initialize object


There are 3 ways to initialize object in Java.

1. By reference variable
2. By method
3. By constructor

1) Object and Class Example: Initialization through reference

Initializing an object means storing data into the object. Let's see a simple example where we
are going to initialize the object through a reference variable.

Amit Srivastava (M.Tech. MNNIT)


5

File: TestStudent2.java

class Student{
int id;
String name;
}
class TestStudent2{
public static void main(String args[]){
Student s1=new Student();
s1.id=101;
s1.name="Sonoo";
System.out.println(s1.id+" "+s1.name);//printing members with a white space
}
}

2) Object and Class Example: Initialization through method

In this example, we are creating the two objects of Student class and initializing the value to
these objects by invoking the insertRecord method. Here, we are displaying the state (data) of
the objects by invoking the displayInformation() method.

File: TestStudent4.java

class Student{
int rollno;
String name;
void insertRecord(int r, String n){
rollno=r;
name=n;
}
void displayInformation(){System.out.println(rollno+" "+name);}
}
class TestStudent4{
public static void main(String args[]){
Student s1=new Student();
Student s2=new Student();
s1.insertRecord(111,"Karan");
s2.insertRecord(222,"Aryan");
s1.displayInformation();
s2.displayInformation();
}
}

Amit Srivastava (M.Tech. MNNIT)


6

In the above figure, object gets the memory in heap memory area. The reference variable
refers to the object allocated in the heap memory area. Here, s1 and s2 both are reference
variables that refer to the objects allocated in memory.

3) Object and Class Example: Initialization through a constructor

We will learn about constructors in Java later.

Object and Class Example: Employee

Let's see an example where we are maintaining records of employees.

File: TestEmployee.java

class Employee{
int id;
String name;
float salary;
void insert(int i, String n, float s) {
id=i;
name=n;
salary=s;
}
void display(){System.out.println(id+" "+name+" "+salary);}
}
public class TestEmployee {
public static void main(String[] args) {
Employee e1=new Employee();
Employee e2=new Employee();
Employee e3=new Employee();

Amit Srivastava (M.Tech. MNNIT)


7

e1.insert(101,"ajeet",45000);
e2.insert(102,"irfan",25000);
e3.insert(103,"nakul",55000);
e1.display();
e2.display();
e3.display();
}
}

Object and Class Example: Rectangle

There is given another example that maintains the records of Rectangle class.

File: TestRectangle1.java
class Rectangle{
int length;
int width;
void insert(int l, int w){
length=l;
width=w;
}
void calculateArea(){System.out.println(length*width);}
}
class TestRectangle1{
public static void main(String args[]){
Rectangle r1=new Rectangle();
Rectangle r2=new Rectangle();
r1.insert(11,5);
r2.insert(3,15);
r1.calculateArea();
r2.calculateArea();
}
}

What are the different ways to create an object in Java?


There are many ways to create an object in java. They are:

 By new keyword
 By newInstance() method
 By clone() method
 By deserialization
 By factory method etc.

Amit Srivastava (M.Tech. MNNIT)


8

Method in Java
In general, a method is a way to perform some task. Similarly, the method in Java is a
collection of instructions that performs a specific task. It provides the reusability of code. We
can also easily modify code using methods. In this section, we will learn what is a method
in Java, types of methods, method declaration, and how to call a method in Java.

What is a method in Java?


A method is a block of code or collection of statements or a set of code grouped together to
perform a certain task or operation. It is used to achieve the reusability of code. We write a
method once and use it many times. We do not require to write code again and again. It also
provides the easy modification and readability of code, just by adding or removing a chunk
of code. The method is executed only when we call or invoke it.

Method Declaration

The method declaration provides information about method attributes, such as visibility,
return-type, name, and arguments. It has six components that are known as method header,
as we have shown in the following figure.

Amit Srivastava (M.Tech. MNNIT)


9

Method Signature: Every method has a method signature. It is a part of the method
declaration. It includes the method name and parameter list.

Access Specifier: Access specifier or modifier is the access type of the method. It specifies
the visibility of the method. Java provides four types of access specifier:

 Public: The method is accessible by all classes when we use public specifier in our
application.
 Private: When we use a private access specifier, the method is accessible only in the
classes in which it is defined.
 Protected: When we use protected access specifier, the method is accessible within
the same package or subclasses in a different package.
 Default: When we do not use any access specifier in the method declaration, Java
uses default access specifier by default. It is visible only from the same package only.

Return Type: Return type is a data type that the method returns. It may have a primitive data
type, object, collection, void, etc. If the method does not return anything, we use void
keyword.

Method Name: It is a unique name that is used to define the name of a method. It must be
corresponding to the functionality of the method. Suppose, if we are creating a method for
subtraction of two numbers, the method name must be subtraction(). A method is invoked
by its name.

Parameter List: It is the list of parameters separated by a comma and enclosed in the pair of
parentheses. It contains the data type and variable name. If the method has no parameter, left
the parentheses blank.

Method Body: It is a part of the method declaration. It contains all the actions to be
performed. It is enclosed within the pair of curly braces.

Amit Srivastava (M.Tech. MNNIT)


10

Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance
of the class is created. At the time of calling constructor, memory for the object is allocated in
the memory. It is a special type of method which is used to initialize the object.

Every time an object is created using the new() keyword, at least one constructor is called.

It calls a default constructor if there is no constructor available in the class. In such case, Java
compiler provides a default constructor by default.

There are two types of constructors in Java: no-arg constructor, and parameterized
constructor.

Note: It is called constructor because it constructs the values at the time of object creation. It
is not necessary to write a constructor for a class. It is because java compiler creates a default
constructor if your class doesn't have any.

Rules for creating Java constructor

There are two rules defined for the constructor.

1. Constructor name must be the same as its class name


2. A Constructor must have no explicit return type
3. A Java constructor cannot be abstract, static, final, and synchronized

Types of Java constructors


There are two types of constructors in Java:

1. Default constructor (no-arg constructor)


2. Parameterized constructor

Amit Srivastava (M.Tech. MNNIT)


11

Java Default Constructor


A constructor is called "Default Constructor" when it doesn't have any parameter.

Syntax of default constructor:

1. <class_name>(){}

Example of default constructor


In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the
time of object creation.

//Java Program to create and call a default constructor


class Bike1{
//creating a default constructor
Bike1(){System.out.println("Bike is created");}
//main method
public static void main(String args[]){
//calling a default constructor
Bike1 b=new Bike1();
}
}

Output:

Bike is created

Rule: If there is no constructor in a class, compiler automatically creates a default


constructor.

Q) What is the purpose of a default constructor?

The default constructor is used to provide the default values to the object like 0, null, etc.,
depending on the type.

Example of default constructor that displays the default values

//Let us see another example of default constructor


//which displays the default values
class Student3{
int id;
Amit Srivastava (M.Tech. MNNIT)
12

String name;
//method to display the value of id and name
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


//creating objects
Student3 s1=new Student3();
Student3 s2=new Student3();
//displaying values of the object
s1.display();
s2.display();
}
}
Test it Now

Output:

0 null
0 null

Explanation:In the above class,you are not creating any constructor so compiler provides
you a default constructor. Here 0 and null values are provided by default constructor.

Java Parameterized Constructor

A constructor which has a specific number of parameters is called a parameterized


constructor.

Why use the parameterized constructor?

The parameterized constructor is used to provide different values to distinct objects.


However, you can provide the same values also.

Example of parameterized constructor

In this example, we have created the constructor of Student class that have two parameters.
We can have any number of parameters in the constructor.

//Java Program to demonstrate the use of the parameterized constructor.


class Student4{
int id;
String name;
//creating a parameterized constructor
Student4(int i,String n){
id = i;
name = n;
}
//method to display the values
void display(){System.out.println(id+" "+name);}

public static void main(String args[]){


Amit Srivastava (M.Tech. MNNIT)
13

//creating objects and passing values


Student4 s1 = new Student4(111,"Karan");
Student4 s2 = new Student4(222,"Aryan");
//calling method to display the values of object
s1.display();
s2.display();
}
}

Amit Srivastava (M.Tech. MNNIT)


14

Method Overloading in Java


If a class has multiple methods having same name but different in parameters, it is known as
Method Overloading. If we have to perform only one operation, having same name of the
methods increases the readability of the program. Suppose you have to perform addition of
the given numbers but there can be any number of arguments, if you write the method such as
a(int, int) for two parameters, and b(int, int, int) for three parameters then it may be difficult
for you as well as other programmers to understand the behavior of the method because its
name differs.

So, we perform method overloading to figure out the program quickly.

Advantage of method overloading


Method overloading increases the readability of the program.

Different ways to overload the method

There are two ways to overload the method in java

1. By changing number of arguments


2. By changing the data type

In Java, Method Overloading is not possible by changing the return type of the method
only.

1) Method Overloading: changing no. of arguments

In this example, we have created two methods, first add() method performs addition of two
numbers and second add method performs addition of three numbers.

In this example, we are creating static methods so that we don't need to create instance for
calling methods.

class Adder{
static int add(int a,int b){return a+b;}
static int add(int a,int b,int c){return a+b+c;}
}
class TestOverloading1{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(11,11,11));
}}

Output:

22
33

Amit Srivastava (M.Tech. MNNIT)


15

2) Method Overloading: changing data type of arguments

In this example, we have created two methods that differs in data type. The first add method
receives two integer arguments and second add method receives two double arguments.

class Adder{
static int add(int a, int b){return a+b;}
static double add(double a, double b){return a+b;}
}
class TestOverloading2{
public static void main(String[] args){
System.out.println(Adder.add(11,11));
System.out.println(Adder.add(12.3,12.6));
}}

Output:

22
24.9

Q) Why Method Overloading is not possible by changing the return type of


method only?

In java, method overloading is not possible by changing the return type of the method only
because of ambiguity. Let's see how ambiguity may occur:

class Adder{
static int add(int a,int b){return a+b;}
static double add(int a,int b){return a+b;}
}
class TestOverloading3{
public static void main(String[] args){
System.out.println(Adder.add(11,11));//ambiguity
}}

Output:

Compile Time Error: method add(int,int) is already defined in class Adder

System.out.println(Adder.add(11,11)); //Here, how can java determine which sum() method


should be called?

Amit Srivastava (M.Tech. MNNIT)


16

Inheritance in Java
Inheritance in Java is a mechanism in which one object acquires all the properties and
behaviors of a parent object. It is an important part of OOPs (Object Oriented programming
system).

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
the parent class. Moreover, you can add new methods and fields in your current class also.

Inheritance represents the IS-A relationship which is also known as a parent-child


relationship.

Why use inheritance in java

 For Method Overriding (so runtime polymorphism can be achieved).


 For Code Reusability.

Terms used in Inheritance

 Class: A class is a group of objects which have common properties. It is a template or


blueprint from which objects are created.
 Sub Class/Child Class: Subclass is a class which inherits the other class. It is also called a
derived class, extended class, or child class.
 Super Class/Parent Class: Superclass is the class from where a subclass inherits the features.
It is also called a base class or a parent class.
 Reusability: As the name specifies, reusability is a mechanism which facilitates you to reuse
the fields and methods of the existing class when you create a new class. You can use the
same fields and methods already defined in the previous class.

The syntax of Java Inheritance

class Subclass-name extends Superclass-name


{
//methods and fields
}

The extends keyword indicates that you are making a new class that derives from an existing
class. The meaning of "extends" is to increase the functionality.

In the terminology of Java, a class which is inherited is called a parent or superclass, and the
new class is called child or subclass.

Java Inheritance Example

Amit Srivastava (M.Tech. MNNIT)


17

As displayed in the above figure, Programmer is the subclass and Employee is the superclass.
The relationship between the two classes is Programmer IS-A Employee. It means that
Programmer is a type of Employee.

class Employee{
float salary=40000;
}
class Programmer extends Employee{
int bonus=10000;
public static void main(String args[]){
Programmer p=new Programmer();
System.out.println("Programmer salary is:"+p.salary);
System.out.println("Bonus of Programmer is:"+p.bonus);
}
}
Programmer salary is:40000.0
Bonus of programmer is:10000

In the above example, Programmer object can access the field of own class as well as of
Employee class i.e. code reusability.

Types of inheritance in java


On the basis of class, there can be three types of inheritance in java: single, multilevel and
hierarchical.

In java programming, multiple and hybrid inheritance is supported through interface only.
We will learn about interfaces later.

Amit Srivastava (M.Tech. MNNIT)


18

Note: Multiple inheritance is not supported in Java through class.

When one class inherits multiple classes, it is known as multiple inheritance. For Example:

Single Inheritance Example


When a class inherits another class, it is known as a single inheritance. In the example given
below, Dog class inherits the Animal class, so there is the single inheritance.

File: TestInheritance.java

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

Amit Srivastava (M.Tech. MNNIT)


19

Output:

barking...
eating...

Multilevel Inheritance Example


When there is a chain of inheritance, it is known as multilevel inheritance. As you can see in
the example given below, BabyDog class inherits the Dog class which again inherits the
Animal class, so there is a multilevel inheritance.

File: TestInheritance2.java

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

Output:

weeping...
barking...
eating...

Hierarchical Inheritance Example


When two or more classes inherits a single class, it is known as hierarchical inheritance. In
the example given below, Dog and Cat classes inherits the Animal class, so there is
hierarchical inheritance.

File: TestInheritance3.java

class Animal{
void eat(){System.out.println("eating...");}
}
class Dog extends Animal{
void bark(){System.out.println("barking...");}
}
class Cat extends Animal{
void meow(){System.out.println("meowing...");}
}
Amit Srivastava (M.Tech. MNNIT)
20

class TestInheritance3{
public static void main(String args[]){
Cat c=new Cat();
c.meow();
c.eat();
//c.bark();//C.T.Error
}}

Output:

meowing...
eating...

Q) Why multiple inheritance is not supported in java?


To reduce the complexity and simplify the language, multiple inheritance is not supported in
java.

Consider a scenario where A, B, and C are three classes. The C class inherits A and B classes.
If A and B classes have the same method and you call it from child class object, there will be
ambiguity to call the method of A or B class.

Since compile-time errors are better than runtime errors, Java renders compile-time error if
you inherit 2 classes. So whether you have same method or different, there will be compile
time error.

class A{
void msg(){System.out.println("Hello");}
}
class B{
void msg(){System.out.println("Welcome");}
}
class C extends A,B{//suppose if it were

public static void main(String args[]){


C obj=new C();
obj.msg();//Now which msg() method would be invoked?
}
}
Compile Time Error

Amit Srivastava (M.Tech. MNNIT)


21

Method Overriding in Java


If subclass (child class) has the same method as declared in the parent class, it is known as
method overriding in Java.

In other words, If a subclass provides the specific implementation of the method that has been
declared by one of its parent class, it is known as method overriding.

Usage of Java Method Overriding

 Method overriding is used to provide the specific implementation of a method which is


already provided by its superclass.
 Method overriding is used for runtime polymorphism

Rules for Java Method Overriding

1. The method must have the same name as in the parent class
2. The method must have the same parameter as in the parent class.
3. There must be an IS-A relationship (inheritance).

Understanding the problem without method overriding

Let's understand the problem that we may face in the program if we don't use method
overriding.

//Java Program to demonstrate why we need method overriding


//Here, we are calling the method of parent class with child
//class object.
//Creating a parent class
class Vehicle{
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike extends Vehicle{
public static void main(String args[]){
//creating an instance of child class
Bike obj = new Bike();
//calling the method with child class instance
obj.run();
}

Output:

Vehicle is running

Problem is that I have to provide a specific implementation of run() method in subclass that is
why we use method overriding.

Amit Srivastava (M.Tech. MNNIT)


22

Example of method overriding

In this example, we have defined the run method in the subclass as defined in the parent class
but it has some specific implementation. The name and parameter of the method are the
same, and there is IS-A relationship between the classes, so there is method overriding.

//Java Program to illustrate the use of Java Method Overriding


//Creating a parent class.
class Vehicle{
//defining a method
void run(){System.out.println("Vehicle is running");}
}
//Creating a child class
class Bike2 extends Vehicle{
//defining the same method as in the parent class
void run(){System.out.println("Bike is running safely");}

public static void main(String args[]){


Bike2 obj = new Bike2();//creating object
obj.run();//calling method
}
}

Output:

Bike is running safely

A real example of Java Method Overriding

Consider a scenario where Bank is a class that provides functionality to get the rate of
interest. However, the rate of interest varies according to banks. For example, SBI, ICICI and
AXIS banks could provide 8%, 7%, and 9% rate of interest.

Java method overriding is mostly used in Runtime Polymorphism which we will learn in
next pages.

//Java Program to demonstrate the real scenario of Java Method Overriding


//where three classes are overriding the method of a parent class.
//Creating a parent class.
class Bank{
int getRateOfInterest(){return 0;}
}
Amit Srivastava (M.Tech. MNNIT)
23

//Creating child classes.


class SBI extends Bank{
int getRateOfInterest(){return 8;}
}

class ICICI extends Bank{


int getRateOfInterest(){return 7;}
}
class AXIS extends Bank{
int getRateOfInterest(){return 9;}
}
//Test class to create objects and call the methods
class Test2{
public static void main(String args[]){
SBI s=new SBI();
ICICI i=new ICICI();
AXIS a=new AXIS();
System.out.println("SBI Rate of Interest: "+s.getRateOfInterest());
System.out.println("ICICI Rate of Interest: "+i.getRateOfInterest());
System.out.println("AXIS Rate of Interest: "+a.getRateOfInterest());
}
}

Amit Srivastava (M.Tech. MNNIT)


24

Access Modifiers in Java


There are two types of modifiers in Java: access modifiers and non-access modifiers.

The access modifiers in Java specifies the accessibility or scope of a field, method,
constructor, or class. We can change the access level of fields, constructors, methods, and
class by applying the access modifier on it.

There are four types of Java access modifiers:

1. Private: The access level of a private modifier is only within the class. It cannot be
accessed from outside the class.
2. Default: The access level of a default modifier is only within the package. It cannot
be accessed from outside the package. If you do not specify any access level, it will be
the default.
3. Protected: The access level of a protected modifier is within the package and outside
the package through child class. If you do not make the child class, it cannot be
accessed from outside the package.
4. Public: The access level of a public modifier is everywhere. It can be accessed from
within the class, outside the class, within the package and outside the package.

Understanding Java Access Modifiers

Let's understand the access modifiers in Java by a simple table.

Access within within outside package by outside


Modifier class package subclass only package
Private Y N N N
Default Y Y N N
Protected Y Y Y N
Public Y Y Y Y

Amit Srivastava (M.Tech. MNNIT)


25

Java Object finalize() Method


Finalize() is the method of Object class. This method is called just before an object is garbage
collected. finalize() method overrides to dispose system resources, perform clean-up activities
and minimize memory leaks.

Syntax
1. protected void finalize() throws Throwable

Throw
Throwable - the Exception is raised by this method

Example 1
public class JavafinalizeExample1 {
public static void main(String[] args)
{
JavafinalizeExample1 obj = new JavafinalizeExample1();
System.out.println(obj.hashCode());
obj = null;
// calling garbage collector
System.gc();
System.out.println("end of garbage collection");

}
@Override
protected void finalize()
{
System.out.println("finalize method called");
}
}

Amit Srivastava (M.Tech. MNNIT)


26

Final Keyword In Java


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

1. variable
2. method
3. class

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

1) Java final variable


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

Example of final variable

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

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

Amit Srivastava (M.Tech. MNNIT)


27

2) Java final method


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

Example of final method

class Bike{
final void run(){System.out.println("running");}
}

class Honda extends Bike{


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

public static void main(String args[]){


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

3) Java final class


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

Example of final class

final class Bike{}

class Honda1 extends Bike{


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

public static void main(String args[]){


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

Amit Srivastava (M.Tech. MNNIT)


28

Abstract class in Java


A class which is declared with the abstract keyword is known as an abstract class in Java. It
can have abstract and non-abstract methods (method with the body).

Abstraction in Java

Abstraction is a process of hiding the implementation details and showing only functionality
to the user.

Another way, it shows only essential things to the user and hides the internal details, for
example, sending SMS where you type the text and send the message. You don't know the
internal processing about the message delivery.

Abstraction lets you focus on what the object does instead of how it does it.

Ways to achieve Abstraction

There are two ways to achieve abstraction in java

1. Abstract class (0 to 100%)


2. Interface (100%)

Abstract class in Java

A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.

Points to Remember

An abstract class must be declared with an abstract keyword.

 It can have abstract and non-abstract methods.


 It cannot be instantiated.
 It can have constructors and static methods also.
 It can have final methods which will force the subclass not to change the body of the
method.

Amit Srivastava (M.Tech. MNNIT)


29

Example of abstract class

1. abstract class A{}

Abstract Method in Java

A method which is declared as abstract and does not have implementation is known as an
abstract method.

Example of abstract method

1. abstract void printStatus();//no method body and abstract

Example of Abstract class that has an abstract method

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

abstract class Bike{


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

Amit Srivastava (M.Tech. MNNIT)

You might also like