[Go to site: main page, start]

0% found this document useful (0 votes)
13 views37 pages

Java Classes and Objects Explained

Uploaded by

lohithdadi64
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)
13 views37 pages

Java Classes and Objects Explained

Uploaded by

lohithdadi64
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

UNIT-II

Classes and Objects

Class:

Class is a collection of similar type of objects.

Class defines a new data type that can be used for creating objects.

Declaration of class:

In JAVA language, class declaration can be done by using the following syntax.

Syntax:

class classname
{
datatype instance_var1;
datatype instance_var2;
.
.
datatype instance_varn;
returntype methodname1(parameter_list)
{
//body
}
.
.
returntype methodnamen(parameter_list)
{
//body
}
}

Variables which are declared inside a class are called as instance variables. Because
each instance of a class can hold a separate copy of these variables.

Class also contains n number of methods which are used to perform operations on data.

Variables and methods which are defined inside a class are collectively known as
members of a class.

Example:

class Box
{

double width, height, depth;

}
After defining a class, by using that class we can create any number of objects.

Creation of Object:

Object creation can be done in two steps.

In first step, class variable is created or declared by using the class name.

Syntax:

classname class_var;

In second step, the memory is allocated for an object at run time using new operator.

Syntax:

Class_var=new classname();

Here parenthesis followed by classname represents a constructor.

Constructor is used to initialize the instance variables.

If the programmer not writing any constructor in a class, then JAVA compiler provides
one default constructor.

The above two steps are combined into a single statement as follows.

classname class_var=new classname();

Example:

Box b1=new Box();

After creating objects, we can access the class members using those objects.

To access instance variables, the following syntax is used.

Syntax:

[Link]=value;

To call and execute any method in a class, the following syntax is used.

Syntax:

[Link]();
Write a program to illustrate the use of class and objects.

//program to illustrate the use of class and objects.

class Box

double width, height, depth;

class BoxDemo

public static void main(String args[])

Box b1=new Box();

double vol;

[Link]=15.35;

[Link]= 20.56;

[Link]=10.34;

vol=[Link]*[Link]*[Link];

[Link](“Volume is “+vol);

Output: Volume is 3263.2626399999995

Defining methods or Adding methods to a class:

General form of a method is as follows

returntype method_name(parameter_list)
{
//body of the method
}

Here returntype represents the type of the data returned by the method. This can be
any valid type including class types that we create.

If the method does not return a value, its return type must be void.

method_name is any valid identifier.


parameter_list is a sequence of type and identifier pairs separated by commas.

If the method has no parameters, then parameter_list is empty.

Example:

In the above example program, we are calculating volume of a box in BoxDemo class.

Now we are calculating the volume of a box in Box class by adding method to Box class.

class Box

double width, height, depth;

void volume()

[Link](“Volume is “+ (width*height*depth));

class BoxDemo

public static void main(String args[])

Box b1=new Box();

Box b2=new Box();

[Link]=10.25;

[Link]=20.35;

[Link]=15.45;

[Link]=3.45;

[Link]=6.78;

[Link]=9.85;

[Link]();

[Link]();
}

Output:

Volume is 3222.676875

Volume is 230.40135

Methods returning values:

class Box

double width, height, depth;

double volume()

return width*height*depth;

class BoxDemo

public static void main(String args[])

Box b1=new Box();

Box b2=new Box();

double vol;

[Link]=10.25;

[Link]=20.35;

[Link]=15.45;

[Link]=3.45;

[Link]=6.78;

[Link]=9.85;

vol=[Link]();

[Link](“Volume is “+vol);
vol=[Link]();

[Link](“Volume is “+vol)

Output:

Volume is 3222.676875

Volume is 230.40135

Adding a method that takes parameters:

Parameters allow a method to be generalized.

Parameterized method can operate on variety of data and/or be used in number of


slightly different situations.

class Box

double width, height, depth;

double volume()

return width* height * depth;

void setDim(double w, double h, double d)

width=w;

height=h;

depth=d;

class BoxDemo

public static void main(String args[])

{
Box b1=new Box();

Box b2=new Box();

double vol;

[Link](2.35,4.65,6.78);

[Link](5.67, 7.89,8.97);

vol=[Link]();

[Link](“Volume is “+vol);

vol=[Link]();

[Link](“Volume is “+vol);

Output: Volume is 74.08845000000002

Volume is 401.28461100000004

Overloaded Methods:

In JAVA language, it is possible to define two or more methods within a same class with
same name but with different number and/or types of arguments.

Then the methods are said to be overloaded and the process is referred as method
overloading.

Method overloading is one of the ways to achieve polymorphism.

Method overloading is an example for compile time polymorphism.

When overloaded method is invoked, JAVA compiler uses the type and/or number of
arguments to determine the method which is to be executed.

Write a program to illustrate method overloading.

class OverLoad

void display()

[Link](“No Parameters”);

void display(int a)
{

[Link](“a= “+a);

void display(int a, int b)

[Link](“a= “+a+” “+”b= “+b);

double display(double a)

[Link](“double a= “+a);

return a*a;

class OverLoadDemo

public static void main(String args[])

OverLoad ol=new OverLoad();

[Link]();

[Link](10);

[Link](10,20);

double result=[Link](3.5);

[Link](“Result= “+result);

}
Output: No Parameters
a= 10
a= 10 b= 20
double a= 3.5
Result= 12.25
In some cases, JAVA’s automatic type conversion can play a role in overloaded
resolution.

For example, consider the following program

class OverLoad

void display()

[Link](“No Parameters”);

void display(int a,int b)

[Link](“a= “+a+”b= “+b);

void display(double a)

[Link](“double a=”+a);

class OverLoadDemo

public static void main(String args[])

OverLoad ol=new OverLoad();

[Link]();

[Link](10,20);

[Link](10);

[Link](15.65);

}
Output:
No Parameters
a= 10b= 20
double a=10.0
double a=15.65

Here we are not defined a method display(int) in OverLoad class. Therefore when a
displaly() is called with an integer argument in OverLoadDemo, no matching method is
found. However, JAVA can automatically converts integer to double and this conversion can
be used to resolve the call.

Recursive methods:

A method which is called by itself is called as recursive method.

Process of calling recursive method is known as recursion.

Write a program to illustrate recursion.


//program to illustrate recursion

import [Link].*;

class Factorial
{
int fact(int n)
{
if(n==0||n==1)

return 1;

else
return n*fact(n-1);
}
}
class Recursion
{
public static void main(String args[])
{
int val;
Factorial f=new Factorial();
Scanner sc=new Scanner([Link]);
[Link](“enter one number”);
val=[Link]();
[Link](“Factorial of “+val+”is ”+[Link](val));
}
}

Output:
enter one number
5
Factorial of 5is 120
Constructors:

Constructor is a special method which is used to initialize the instance variables.

Rules for writing constructors:

1) Constructor name is same as class name in which it resides.


2) Constructor doesn’t have any return type not even void also.
3) Constructor cannot be abstract, final, static and synchronized.
4) Access modifiers can be used for declaration of constructors.

Note: When constructor is not defined in a class, JAVA compiler provides one default
constructor to a class automatically. The default constructor automatically initializes the
instance variables to their default values.

Constructors cannot be called explicitly; Constructor is automatically called when an


object is created.

Types of constructors:

There are two types of constructors in JAVA.

1) Zero-argument constructor(Default constructor)


2) Parameterized constructor

Zero-argument constructor:

A constructor that has no parameters is called as zero-argument constructor.

Syntax:

classname()
{
//body of the constructor
}
Example:

class Box

double width, height, depth;

Box()

[Link](“Constructing Box... ”);

width=10.25;

height=12.35;
depth=15.45;

double volume()

return width*height*depth;

class ConstructorDemo

public static void main(String args[])

Box b1=new Box();

Box b2=new Box();

double vol;

vol=[Link]();

[Link](“Volume is “+vol);

vol=[Link]();

[Link](“Volume is “+vol);

Parameterized Constructor:

While the Box() constructor in the previous program does initialize a Box object, it is
not very useful because all the boxes have same dimensions.

To construct Box objects of various dimensions, we have to add parameters to


constructor.

A constructor that has parameters is called as parameterized constructor.


Syntax:

classname(parameter_list)
{
//body of the constructor
}

Example:

class Box

double width, height, depth;

Box(double w, double h, double d)

[Link](“Constructing Box ”);

width=w;

height=h;

depth=d;

double volume()

return width*height*depth;

class ConstructorDemo

public static void main(String args[])

Box b1=new Box(10.25,13.35,15.45);

Box b2=new Box(23.45,34.56,56.78);

double vol;
vol=[Link]();

[Link](“Volume is “+vol);

vol=[Link]();

[Link](“Volume is “+vol);

Constructor overloading:

Like methods, constructors can also be overloaded.

When do we need Constructor Overloading?

Sometimes there is a need of initializing an object in different ways. This can be done
using constructor overloading.

Constructor overloading means writing two or more constructors with different types
or number of parameters.

Example:
class Box {
double width, height, depth;
Box(double w, double h, double d)
{
width = w;
height = h;
depth = d;
}
// constructor used when no dimensions
Box() {
width = height = depth = 0;
}
// constructor used when cube is created
Box(double len) {
width = height = depth = len;
}
double volume() { return width * height * depth; }
}
class Test {
public static void main(String args[])
{
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
vol = [Link]();
[Link]("Volume of mybox1 is " + vol);
vol = [Link]();
[Link]("Volume of mybox2 is " + vol);
vol = [Link]();
[Link]("Volume of mycube is " + vol);
}
}
Output: Volume of mybox1 is 3000.0
Volume of mybox2 is 0.0
Volume of mycube is 343.0

Types of Variables in Java


1. Local Variables
2. Instance Variables
3. Static Variables
1. Local Variables
A variable defined within a block or method or constructor is called a local variable.
 These variables are created when the block is entered, or the function is called and
destroyed after exiting from the block or when the call returns from the function.
 The scope of these variables exists only within the block in which the variables are
declared, i.e., we can access these variables only within that block.
 Initialization of the local variable is mandatory before using it in the defined scope.
2. Instance Variables
Instance variables are non-static variables and are declared in a class outside of any
method, constructor, or block.
 As instance variables are declared in a class, these variables are created when an
object of the class is created and destroyed when the object is destroyed.
 Unlike local variables, we may use access specifiers for instance variables. If we do not
specify any access specifier, then the default access specifier will be used.
 Instance variables can be accessed only by creating objects.
3. Static Variables
 These variables are declared similarly to instance variables. The difference is that
static variables are declared using the static keyword within a class outside of any
method, constructor, or block.
 Unlike instance variables, we can only have one copy of a static variable per class,
irrespective of how many objects we create.
 Static variables are created at the start of program execution and destroyed
automatically when execution ends.
 Initialization of a static variable is not mandatory.
 If we access a static variable without the class name, the compiler will automatically
append the class name. But for accessing the static variable of a different class, we
must mention the class name as 2 different classes might have a static variable with
the same name.
 Static variables cannot be declared locally inside an instance method.
//Example on Local, instance , static variables
class Example {
// Declared static variable
static String name = "Shubham Jain";
int a=20; //Instance variable
public static void main(String[] args)
{
double x=22.3; //Local variable
[Link]("Name is : " + name);
[Link]("local varaible is "+x);
//[Link]("Instance variable is " +a); //Error
Example ob1=new Example();
[Link]("Instance variable is " +ob1.a);
}
}
Output: Name is : Shubham Jain
local varaible is 22.3
Instance variable is 20

static keyword in JAVA:


 The static keyword in Java is used for memory management mainly. We can
apply static keyword with variables, methods, blocks and nested classes. The
static keyword belongs to the class than an instance of the class.

 When a member is declared static, it can be accessed before any objects of its class
arecreated and without reference to any object.

 Instance variables declared as static are essentially global variables. When


objects of itsclass are declared, no copy of static variable is made. Instead, all
objects of the class share the same static variable.

Java static method


If you apply static keyword with any method, it is known as static method.

o A static method belongs to the class rather than the object of a class.
o A static method can be invoked without the need for creating an instance of a class.
o A static method can access static data member and can change the value of it.
To call a static method from outside its class, we use class name and dot operator
as follows.
[Link]();
o
o Here classname is the name of the class in which static method is declared.

o In the same way, static variable can be accessed by using its class name and dot
operator as follows.

classname.variable_name;
o

Note: Methods declared as static have several [Link] can only call other static methods.
Then can only directly access static variables.

// EXAMPLE ON STATIC METHOD

class Student{
int rollno;
String name;
static String college = "BITS";

static void change(){


college = "VIT";
}

Student(int r, String n)
{
rollno = r;
name = n;
}

void display(){
[Link](rollno+" "+name+" "+college);
}
}
public class TestStaticMethod{
public static void main(String args[]){
[Link]();//calling change method
//creating objects
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
//calling display method
[Link]();
[Link]();
[Link]();
}
}
Output:
111 Karan VIT
222 Aryan VIT
333 Sonoo VIT
Java static block
o Is used to initialize the static data member.
o It is executed before the main method at the time of classloading

// Write a program to illustrate static variables, methods and blocks.

class Demo{
static int count;
static void count()
{
count++;
[Link](count);
}
static
{
count=1;
[Link](count);
}
}
class D{
public static void main(String[] args)
{
[Link]();
[Link]();
}
}
OUTPUT:
1
2
3

Access Modifiers in Java

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 (accessible within the class where defined)

2) default (when no access modifier is specified)

3) protected (accessible only to classes that subclass your class directly within the

current or different package)

4) public (accessible from any class)


the classes have two access modifiers

1) public

2) default (when no access modifier is specified)

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.

To understand public and private access modifiers, consider the following program.

// This program demonstrates access modifiers

class Test
{
int a=22;
public int b=10;;
private int c=20;
protected int x=100;
int getc()
{
return c;
}
}
class AccessTest
{
public static void main(String args[]) {
Test ob = new Test();
[Link](ob.a);
[Link](ob.b);
int res=[Link]();
//[Link](ob.c); //error
[Link](res);
[Link](ob.x);

}
}

Output: 22
10
20
100

this keyword:

In Java, this is a keyword which is used to refer current object of a class. We can use it
to refer any member of the class. It means we can access any instance variable and
method by using this keyword.

The main purpose of using this keyword is to solve the confusion when we have same
variable name for instance and local variables.

We can use this keyword for the following purpose.

a) this can be used to refer current class instance variable.


b) this() can be used to invoke current class constructor.
c) this can be used to invoke current class method (implicitly)
d) this can be passed as an argument in the method call.

a) this keyword is used to refer to current object:

In this example, we have an instance variables and a constructor that have


parameters with same name as instance variables. Now, we will use this to assign
values of parameters to instance variables.
Example:
class Square
{
int side;
Square(int side)
{
[Link] = side;
}
void display(){
[Link](side*side);
}
}
class SquareDemo
{
public static void main(String[] args){
Square s1 = new Square(4);
[Link]();
}
}

Output: 16

b) Calling constructor using this keyword(constructor chaining):


We can call a constructor from inside another constructor using this keyword.
class Square
{
int side;
Square() {
this(20);
}

Square(int side)
{
[Link] = side;
}
void display(){
[Link](side*side);
}
}
class SquareDemo
{
public static void main(String[] args){
Square s1 = new Square();
[Link]();
}
}
Output: 400

c) Accessing method using this keyword: You may invoke the method of the current class by using
the this keyword. If you don't use the this keyword, compiler automatically adds this keyword while
invoking the method.
class Square
{
int side;
Square(int side)
{
[Link] = side;
}
void getarea(){
[Link](side*side);
}
void display(){
[Link](); // same as getarea();
}
}
class SquareDemo
{
public static void main(String[] args){
Square s1 = new Square(2);
[Link]();
}
}

d) Passing this as an argument


We can use this keyword to pass the current object as an argument to a method.
//Example
class Square
{
int side;
Square(int side)
{

[Link] = side;
[Link]([Link]*[Link]);
area(this);
[Link]([Link]*[Link]);
}
void area(Square x)
{
[Link]=7;
}

}
class SquareDemo
{
public static void main(String[] args){
Square s1 = new Square(2);
}
}
Output:
4
49

Inheritance in JAVA:

Inheritance is the process by which one object acquires the properties of another object.

(or)

Deriving a class from another class is called as inheritance.

Superclass (or) Parent class (or) base class: A class that is inherited is called as

superclass.

Subclass (or) Child class (or) derived class: A class that does inheriting is called as
subclass.

Types of inheritance:
Generally there are 5 types of inheritance

They are

1) Single inheritance
2) Multiple inheritance
3) Multi-level inheritance
4) Hierarchical inheritance
5) Hybrid inheritance

Single inheritance:

Deriving a sub class from single super class is called as single inheritance

Multiple inheritance:

Deriving a sub class from more than one super class is called as multiple inheritance.

Note: JAVA does not support multiple inheritance directly. We can achieve multiple
inheritance in JAVA by using interfaces.

Multi-level inheritance:

In multi-level inheritance, one sub class is derived from another sub class. Hence one
sub class becomes super class for a new class.
Hierarchical inheritance:
Deriving more than one sub class from a single super class is called as hierarchical inheritance.

Hybrid inheritance:

Hybrid inheritance is a combination of two or more types of inheritances.

Note: JAVA does not support hybrid inheritance.

In JAVA language, in order to derive a class from another class we use extends keyword.

General form of deriving a class as follows.

Syntax:

class sub_class_name extends super_class_name


{
//body of a class
}
By doing inheritance, all the behaviour of superclass is available in sub class. That
means we can access superclass members by using subclass objects.
Note: Although a subclass includes all the members of its superclass, it cannot access
the member of the superclass that has been declared as private.

//Program to illustrate single inheritance


class A{
void display1(){
[Link]("Iam in class A");
}
}
class B extends A{
void display2(){
[Link]("Iam in class B");
}
}
class Demo{
public static void main(String[] args){
B ob=new B();
ob.display1();
ob.display2();
}
}
Output: Iam in class A

Iam in class B

//Program to illustrate multilevel inheritance


class A{
void display1(){
[Link]("Iam in class A");
}
}
class B extends A{
void display2(){
[Link]("Iam in class B");
}
}
class C extends B{
void display3(){
[Link]("Iam in class C");
}
}
class Demo{
public static void main(String[] args){
C ob=new C();
ob.display1();
ob.display2();
ob.display3();
}
}
Output:
Iam in class A
Iam in class B
Iam in class C

//Program to illustrate Hierarchical inheritance

class A{
void display1(){
[Link]("Iam in class A");
}
}
class B extends A{
void display2(){
[Link]("Iam in class B");
}
}
class C extends A{
void display3(){
[Link]("Iam in class C");
}
}
class Demo{
public static void main(String[] args){
C ob=new C();
ob.display1();
ob.display3();
}
}
Output:
Iam in class A
Iam in class C

super keyword:
Whenever a subclass needs to refer to its immediate superclass, it can do so by use of
the keyword super. The keyword “super” came into the picture with the concept of
Inheritance.

Usage of Java super Keyword


1. super can be used to invoke immediate parent class members(fields & methods).
2. super() can be used to invoke immediate parent class constructor.

1. to refer immediate parent class memebers:

Here member can be either an instance variable or a method name

super keyword (in sub class) is to access the hidden members of its immediate super class. To
understand this let’s consider the following example:
class A
{
int x;
public void display()
{
[Link]("This is display in A");
}
}
class B extends A
{
int x=10;
public void display()
{
[Link]("Value of x in A is: "+ super.x); //parent class varaible
[Link](); //parent class method
[Link]("This is display in B");
}
}
class Driver
{
public static void main(String[] args)
{
B obj = new B();
[Link]();
}
}
Output:
Value of x in A is: 0
This is display in A
This is display in B

2. to invoke superclass constructor:

A subclass can call a constructor defined by its superclass by using the following syntax.

Syntax:

super(arg_list);

Here arg_list specifies any arguments needed by the constructor in the superclass.

super() must always be the first statement executed inside a subclass constructor.

//Program to illustrate calling superclass constructor using super keyword

class Person{
int id;
String name;
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,"ankit",45000f);

[Link]();

}
}

Output:
1 ankit 45000.0

Polymorphism in Java

Polymorphism in Java can be done in two ways, method overloading and method
overriding. There are two types of polymorphism in Java.

1. Compile-time polymorphism
2. Runtime polymorphism.
Compile Time Polymorphism:
 Whenever an object is bound with its functionality at the compile time, this is known as the
compile-time polymorphism.
 At compile-time, java knows which method to call by checking the method signatures. So this
is called compile-time polymorphism or static or early binding.
 Compile-time polymorphism is achieved through method overloading.
 Method Overloading says you can have more than one function with the same name in one
class having a different prototype.

Method overriding:

In a class hierarchy, when a method in a subclass has the same name and type signature
as a method in its superclass, then the method in the subclass is said to override the
method in the super class.
When an overridden method is called from within its subclass, it will always refer to the
version of that method defined by the subclass. The version of the method defined by
the super class will be hidden.
Usage of Java Method Overriding
o Method overriding is used to provide the specific implementation of a method which is
already provided by its superclass.
o 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).

//Program to illustrate method overriding


class A
{
void show()
{
[Link]("superclass method");
}
}
class B extends A
{
void show()
{

[Link]("subclass method");
}
}
class OverridingDemo
{
public static void main(String args[])
{
B b1=new B();
[Link]();
}
}
Output: subclass method
Note: To call method defined by superclass , the keyword super is used in subclass method.
class A
{
void show()
{
[Link]("superclass method");
}
}
class B extends A
{
void show()
{
[Link]();
[Link]("subclass method");
}
}
class OverridingDemo
{
public static void main(String args[])
{
B b1=new B();

[Link]();
}
}

Output:

superclass method
subclass method

 A static method cannot be overridden.


 It is because the static method is bound with class whereas instance method is bound with
an object. Static belongs to the class area, and an instance belongs to the heap area.

Dynamic Method Dispatch or Runtime Polymorphism in Java


 Dynamic method dispatch is the mechanism by which a call to an overridden
method isresolved at run time, rather than compile time.
 In Dynamic Method Dispatch, superclass reference variable can refer the
subclass objects. This is also known as upcasting. By using superclass reference
variable, we can call the overridden methods.
//Program that illustrates Dynamic method dispatch

class A
{
void show()
{
[Link]("super class method");
}
}
class B extends A
{
void show()
{
[Link]("sub class1 method");
}
}
class C extends B
{
void show()
{
[Link]("sub class2 method");
}
}
class Demo{
public static void main(String args[])
{

A a1=new A();
A b1=new B();
A c1=new C();
[Link]();
[Link]();

[Link]();
}
}
Output: super class method
sub class1 method
sub class2 method

Abstract classes and methods:

To define generalized behaviour of a class, we use abstract methods and abstract


classes.

Abstract method: A method which is not implemented is called as abstract method.

Abstract methods can be declared using the keyword ‘abstract’ by using the following
syntax

abstract returntype method_name(parameter_list);

Example:

abstract void display();

Abstract class: Any class which contains at least one abstract method is called as
abstract class.

To declare abstract class, the keyword ‘abstract’ is used before the class declaration.

Syntax:

abstract class classname


{
.............
..............
...............
}

In abstract class, in addition to abstract methods, concrete methods are also available.

Abstract methods should be implemented in the sub classes of abstract class. If sub class
also not implemented abstract method then make the sub class also as abstract.

We cannot create objects for abstract classes.

We can create only reference variable for abstract classes.

Write a java program for abstract class to find areas of different shapes
//Program to find areas of different shapes using abstract class
abstract class Shape
{
int dim1,dim2;
Shape(int dim1,int dim2)
{
this.dim1=dim1;
this.dim2=dim2;
}
abstract double area();
}
class Triangle extends Shape
{
Triangle(int a,int b)
{
super(a,b);
}
double area()
{
double a1=(dim1*dim2)/2;
return a1;
}
}
class AbstractDemo
{
public static void main(String args[])
{
Shape s;
Triangle t=new Triangle(10,20);
s=t;

[Link]([Link]());
}
}
Output: 100
Final keyword:

The final keyword in java is used to restrict the user


Final is a non-access modifier applicable only to a variable, a method or a [Link]
final keyword is used to perform 3 tasks as follows

1. To create constant variables


2. To prevent method overriding
3. To prevent Inheritance

Final variables:

Once we declare a variable with the final keyword, we can’t change its value again. If we
attempt to change the value of the final variable, then we will get a compilation error.

You can initialize a final variable when it is declared. A final variable is called blank
final variable, if it is not initialized while declaration.

We can initialize a blank final variable inside the constructor of the class.
Example:
class Main {
public static void main(String[] args) {
// create a final variable
final int AGE = 32;
// try to change the final variable
AGE = 45;
[Link]("Age: " + AGE);
}
}

The above code gives compilation error

final methods:

A method which is declared with the keyword final cannot be overridden.

If we try to override final method, then it will give compile time error.

Example
class A
{

final void show()

[Link](“final method”);

class B extends A

void show() //This will give compile time error

[Link](“sub class method”);


}

Final classes:

A class which is declared with the keyword final cannot be inherited.

Example:

final class A

{
void show()

[Link](“super class method”);

class B extends A //This will give a compile time error

void show()

[Link](“sub class method”);

Method overloading vs Method overriding


The differences between Method Overloading and Method Overriding in
Java are as follows:

Method Overloading Method Overriding

Method overloading is a compile-time


Method overriding is a run-time polymorphism.
polymorphism.

Method overriding is used to grant the specific


Method overloading helps to increase the
implementation of the method which is already
readability of the program.
provided by its parent class or superclass.

It is performed in two classes with inheritance


It occurs within the class.
relationships.

Method overloading may or may not


Method overriding always needs inheritance.
require inheritance.

In method overloading, methods must


In method overriding, methods must have the
have the same name and different
same name and same signature.
signatures.

In method overloading, the return type


In method overriding, the return type must be the
can or can not be the same, but we just
same or co-variant.
have to change the parameter.
Method Overloading Method Overriding

Static binding is being used for Dynamic binding is being used for overriding
overloaded methods. methods.

It gives better performance. The reason behind


Poor Performance due to compile time
this is that the binding of overridden methods is
polymorphism.
being done at runtime.

Private and final methods can be


Private and final methods can’t be overridden.
overloaded.

The argument list should be different The argument list should be the same in method
while doing method overloading. overriding

You might also like