0% found this document useful (0 votes)
5 views36 pages

JAVA UNIT II Final

This document provides an overview of classes and objects in Java, detailing their definitions, components, and the fundamental concepts of Object-Oriented Programming (OOP) such as inheritance, encapsulation, polymorphism, and abstraction. It explains how to declare classes, create objects, and the significance of access modifiers in controlling visibility. Additionally, it covers constructors, methods, and the process of object creation and initialization in Java.
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)
5 views36 pages

JAVA UNIT II Final

This document provides an overview of classes and objects in Java, detailing their definitions, components, and the fundamental concepts of Object-Oriented Programming (OOP) such as inheritance, encapsulation, polymorphism, and abstraction. It explains how to declare classes, create objects, and the significance of access modifiers in controlling visibility. Additionally, it covers constructors, methods, and the process of object creation and initialization in Java.
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/ 36

UNIT II

Classes and Objects: Introduction, Class Declaration and Modifiers, Class Members, Declaration
of Class Objects, Assigning One Object to Another, Access Control for Class Members, Accessing
Private Members of Class, Constructor Methods for Class, Overloaded Constructor Methods,
Nested Classes, Final Class and Methods, Passing Arguments by Value and by Reference,
Keyword this. Methods: Introduction, Defining Methods, Overloaded Methods, Overloaded
Constructor Methods, Class Objects as Parameters in Methods, Access Control, Recursive
Methods, Nesting of Methods, Overriding Methods, Attributes Final and Static.

Java is an Object-Oriented Language. As a language that has the Object-Oriented


feature, Java supports the following fundamental concepts −

• Classes
• Objects
• Polymorphism
• Inheritance
• Encapsulation
Abstraction

• Instance
• Method
• Message Passing
Classes and objects:

Classes and objects are the fundamental components of OOP's. Often there is a confusion
between classes and objects. In this tutorial, we try to tell you the difference between class
and object.

What is Class in Java

Define Class:

• A class is a blueprint for the object. Before we create an object, we first need to define the
class.
• A class is an entity that determines how an object will behave and what the object will
contain. In other words, it is a blueprint or a set of instruction to build a specific type of
object.

Syntax to declare a class:


class Class_name
{
field or variable ;
method like main() and others ;
}

1
Class Members in JAVA: or Components of a Class

There are FIVE members in a class.

1. Variables (States)
2. Methods (Behaviors)
3. Constructor
4. Blocks (Instance/Static Blocks )
5. Inner Classes.

1. Modifiers: A class can be either a public or default access modifier. But the members of class
can be public, private, default, and protected. All these are the access modifiers.
2. Class name: By convention, a class name should begin with a capital letter and subsequent
characters lowercased (for example Student).

2
3. Body: Every class’s body is enclosed in a pair of left and right braces. In the body, a class
can contain the following members.
4.Fields: Fields are data member variables of a class that stores data or value in it. It specifies
the state or properties of the class and its object. It may be a local variable, instance variable,
or static variable.
5.Constructor: A constructor is used to create an object. Every class must be at least one
constructor otherwise, no object can be created of the class.
If you don’t explicitly define a constructor, the compiler automatically adds a default constructor
inside the class. A constructor can be divided into two types, such as default constructor and
user-defined constructor.

6.Method: A method defines an action or behavior of the class that a class’s object can perform.
It has a body within braces. In the body, we write code that performs actions. It may be an
instance method or a static method.
7.Block: A block is mostly used to change the default values of variables. It may be an instance
block or static block.
8. main Method: A class has also the main method that provides the entry point to start the
execution of any program. The main method is static in nature.

public class Human public static void main(String[] args)


{ {
private String name; // Variables Human h = new Human("Superman");
public static int count; h.dream();
public Human(String name) //Constructor System.out.println(Human.count);
{ }
this.name = name; }
}
public void dream () //Method Output:
{
System.out.println(name + " is dreaming to learn
JAVA :)"); Human class has loaded to memory
}
Static //Static Block Superman is dreaming to learn JAVA :)
{
0
System.out.println("Human class has loaded to
memory");
}
private class inner // Inner class
{
public void getHumanName()
{
System.out.println(name);
}}

3
Class - Dogs
Data members - breed, size, color, age etc.
Methods- eat(), run(), sleep(), name().

Example to write main() Method within class:

class Student{ Output:

String name =”Ramesh”; //field or data member or instance variable Ramesh

int rollNo=15;//field or data member or instance variable 15

public static void main(String args[])

Student s1=new Student();//creating an object of Student


System.out.println(s1.name); //accessing member through reference
System.out.println(s1.rollNo);//accessing member through reference
} }

4
Example to write main() Method outside class

// this is a different class Output:


class Student{
Ramesh
String name=”Ramesh”; //field or data member or instance variable
int rollNo=15;//field or data member or instance variable 15
}
//this is main class
class MainClass{
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
System.out.println(s1.name); //accessing member through reference
System.out.println(s1.rollNo);//accessing member through reference
}
}

Object in JAVA:

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:

o An object is a real-world entity.


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

Creating an Object

As mentioned previously, a class provides the blueprints for objects. So basically, an object is
created from a class. In Java, the new keyword is used to create new objects.

There are three steps when creating an object from a class −

• Declaration − A variable declaration with a variable name with an object type.


• Instantiation − The 'new' keyword is used to create the object.
• Initialization − The 'new' keyword is followed by a call to a constructor. This call
initializes the new object.

5
Using new Keyword
Using the new keyword is the most popular way to create an object or instance of the class.
When we create an instance of the class by using the new keyword, it allocates memory (heap)
for the newly created object and also returns the reference of that object to that memory. The
new keyword is also used to create an array. The syntax for creating an object is:

ClassName object = new ClassName();

Create a Class Create an Object


In Java, an object is created from a class. We have already
public class Main created the class named Main, so now we can use this to
{ create objects.
int x = 5; Example:
} Create an object called "myObj" and print the value of x:

public class Main {


int x = 5;

public static void main(String[] args) {


Main myObj = new Main();
System.out.println(myObj.x);
}
}

Multiple Objects
Create two objects of Main: You can create multiple objects of one class:

public class Main {


int x = 5;
public static void main(String[] args) {
Main myObj1 = new Main(); // Object 1
Main myObj2 = new Main(); // Object 2
System.out.println(myObj1.x);
System.out.println(myObj2.x);
}
}

6
Using Multiple Classes
You can also create an object of a class and access it in another class. This is often used
for better organization of classes (one class has all the attributes and methods, while the
other class holds the main() method (code to be executed)).

Remember that the name of the java file should match the class name. In this example, we
have created two files in the same directory/folder:
• Main.java
• Second.java

Main.java
public class Main {
int x = 5;
}
Second.java
class Second {
public static void main(String[] args) {
Main myObj = new Main();
System.out.println(myObj.x);
}
}
How to Initialize object in JAVA:
There is three Ways to initialize object

• By reference variable
• By method
• By constructor

Object Creation and assigning values through reference


class Student Output:
{
Ramboo
String name
int rollNo; 21
}
class MainClass{
public static void main(String args[]){
Student s1=new Student();//creating an object of Student
s1.name = "Ramboo"; //Initialization through reference
s1.rollNo = 21; // Initialization through reference
System.out.println(s1.name+"'s Roll No: "+s1.rollNo);
} }

7
Object Creation and assigning values through method
class Student{ Output:
String name; //field or data member or instance
Ramboo
variable
int rollNo;//field or data member or instance variable 21
void methodforInti(String s, int r)
{
name = s;
rollNo = r;
}
public static void main(String args[]){
Student obj1=new Student();
obj1.methodforInti("Ramboo",21);
System.out.println(obj1.name+"'s Roll No: "+obj1.rollNo);
}
}

Object Creation and assigning values through reference through constructor


class Student{ Output:
String name; //field or data member or instance
Ramboo
variable
int rollNo;//field or data member or instance variable 21

Student(String s, int r) // this is a constructor


{
name = s;
rollNo = r;
}
void methodforDisplay()
{
System.out.println(name+"'s Roll No: "+rollNo);
}
public static void main(String args[]){
Student obj1=new Student("Ramboo",21);
obj1.methodforDisplay();
}}

Assigning One Object to Another: Object Assignment by Value or Reference


In Java, objects are always passed by Reference. Reference is nothing but the starting address
of a memory location where the actual object lies. You can create any number of references to
just One Object. Let us go by an example.

8
public Class Cloud //OUTPUT
{
//OBJ2= RED, OBJ3= RED
String color;
public static void main(String[] args) //Color= RED
{
Cloud obj1 = new Cloud(); Obj2 and Obj 3 are
obj1.color = "RED"; assigned to Obj1 in this

example
Cloud obj2, obj3;
obj2 = obj1; //Assign obj1 to obj2
obj3 = obj2; //Assign obj2 to obj3
System.out.println("OBJ2= " + obj2.color + ", OBJ3= " + obj3.color);
obj2=null; obj3=null;
System.out.print("Color= " + obj1.color);
}
}

Polymorphism
• Existing in many forms is known as
polymorphism.
• For example: to convince the customer
differently, to draw something, for example,
shape, triangle, rectangle, etc.
• In Java, we use method overloading and
method overriding to achieve polymorphism.
• for example, a cat speaks meow, dog barks
woof, etc.

Abstraction
• Hiding internal details and showing
functionality is known as abstraction.
• In Java, we use abstract class and interface
to achieve abstraction.

Inheritance
When one object acquires all the properties and behaviours of a parent object, it is known as
inheritance. It provides code reusability. It is used to achieve runtime polymorphism.

Encapsulation
Binding (or wrapping) code and data together into a single unit are known as encapsulation. For
example, a capsule, it is wrapped with different medicines.

9
A java class is the example of encapsulation. Java bean is the fully encapsulated class because
all the data members are private her

What are Access Modifiers?


Access modifiers are keywords that can be used to control the visibility of fields, methods, and
constructors in a class. The four access modifiers in Java are public, protected, default, and
private.

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.

Access Control for Class Members:

Default Access Specifiers:

A default access modifier in Java has no specific keyword. Whenever the access modifier is not
specified, then it is assumed to be the default. The entities like classes, methods, and variables
can have a default access.

10
A default class is accessible inside the package but it is not accessible from outside the
package.

class BaseClass Output:


{
Hello World
void display() //no access modifier indicates default modifier
{
System.out.println(“Hello World ");
}
}
class Main
{
public static void main(String args[])
{
BaseClass obj = new BaseClass(); //access class with default
scope
obj.display(); //access class method with default scope
}
}

Public Access Modifier:

A class or a method or a data field specified as ‘public’ is accessible from any class or package
in the Java program. The public entity is accessible within the package as well as outside the
package.

class A Output:
{
public void display() Hello World
{
System.out.println("Hello World!!");
}
}
class Main
{
public static void main(String args[])
{
A obj = new A ();
obj.display();
}}

11
Private Access Modifier :
The ‘private’ access modifier is the one that has the lowest accessibility level. The methods and
fields that are declared as private are not accessible outside the class. They are accessible
only within the class which has these private entities as its members.

Note that the private entities are not even visible to the subclasses of the class. A private
access modifier ensures encapsulation in Java.

Some points to be noted regarding the Private Access Modifier.


1. Private access modifier cannot be used for classes and interfaces.
2. The scope of private entities (methods and variables) is limited to the class in
which they are declared.
3. A class with a private constructor cannot create an object of the class from any
other place like the main method.
class TestClass
{
//private variable and method
private int num=100;
private void printMessage(){System.out.println("Hello java");}

}
public class Main{
public static void main(String args[]){
TestClass obj=new TestClass();
System.out.println(obj.num);//try to access private data member - Compile Time Error
obj.printMessage();//Accessing private method - Compile Time Error
}
}

Output:

TestClass.java:7: error: class Main is public, should be declared in a file named Main.java
public class Main{
^
TestClass.java:10: error: num has private access in TestClass
System.out.println(obj.num);//try to access private data member - Compile Time Error
^
TestClass.java:11: error: printMessage() has private access in TestClass
obj.printMessage();//Accessing private method - Compile Time Error
^
3 errors

12
Protected Access Modifier
When methods and data members are declared protected, we can access them within the
same package as well as from subclasses. For example,

class Animal { Output:


// protected method
I am an animal
protected void display() {
System.out.println("I am an animal");
}
}
class Dog extends Animal {
public static void main(String[] args) {

// create an object of Dog class


Dog dog = new Dog();
// access protected method
dog.display();
}}

Constructors in JAVA:

A constructor is a special kind of method that determines how an object is initialized when it’s
created.

Rules for creating Java Constructor

There are basically three rules defined for the constructor.

1. Constructor name must be same as its class name


2. Constructor must have no explicit return type. i.e Constructors do not have a return type
— not even void
3. Constructors are invoked using the new operator when an object is created.
Constructors play the role of initializing objects.

Syntax
Following is the syntax of a constructor –

class ClassName
{
ClassName()
{
}
}

13
Types of Java constructors
1. Default constructor (no-arg constructor)
2. Parameterized constructor.

Example of Default Constructor

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

class Sample{ Output:

This is inside constructor


Sample() // default constructor
{
System.out.println("this is inside constructor");
}
public static void main(String args[]){
Sample b=new Sample();
}
}
class Rectangle Output:
{
Length=10
double length=10;
double width=5; Width=5
Rectangle() // default constructor
{
System.out.println("Length = "+length);
System.out.println("Width = "+width);
}
public static void main(String args[])
{
Rectangle rct = new Rectangle();
}
}

14
Example of Parameterized Constructor

class Rectangle Output:


{
11.5
double length;
double width; 12.5
Rectangle(double l,double w)
{
length=l;
width=w;
System.out.println("Length = "+length);
System.out.println("Width = "+width);
}
public static void main(String args[])
{
Rectangle rct = new Rectangle(11.5,12.5);
}
}

public class MyClass { Output:


int number; Parameterized
public MyClass(int x) { Constructor Called
System.out.println("Parameterized Constructor Called"); Number value is: 4
number=x;
}
public static void main(String[] args)
{
MyClass obj = new MyClass(4); // Parameterized Constructor Called
System.out.println("Number value is: "+obj.number);
}
}

Constructor Overloading in JAVA?

The process of defining more than one constructor with different parameters in a class is
known as constructor overloading. Parameters can differ in number, type or order.

Rules for overloading

• Constructor overloading can appear only in the same class.


• Overloaded constructor MUST change its number of argument or its type.
• Overloaded constructor CAN change the access modifier.

15
Example:
class RectangleArea class Main {
{ String language;
private int length; // constructor with no parameter
private int breadth; Main() {
this.language = "Java";
RectangleArea(int l, int b) { }
length = l; // constructor with a single parameter
breadth = b; Main(String language) {
} this.language = language;
RectangleArea(int side) { }
length = side; public void getName() {
breadth = side; System.out.println("Programming
} Langauage: " + this.language);
}
public int getArea() { public static void main(String[] args) {
return length * breadth; // call constructor with no parameter
} Main obj1 = new Main();
public static void main(String[] args) { // call constructor with a single
RectangleArea rect = new RectangleArea(4, 5); parameter
RectangleArea sq = new RectangleArea(5); Main obj2 = new Main("Python");
System.out.println(rect.getArea()); obj1.getName();
System.out.println(sq.getArea()); obj2.getName();
} }
} }
Output: Output:
20 Programming language: Java
25 Programming language: Python

Nested Classes or Inner Classes:


• A class defined within another class is known as Nested class. The scope of the nested
class is bounded by the scope of its enclosing class.
• We use inner classes to logically group classes and interfaces in one place so that it
can be more readable and maintainable.

class OuterClass
{
int x = 10;
class InnerClass {
int y = 5;
}
}

16
Advantage of Java inner classes:

There are basically three advantages of inner classes in java. They are as follows:

• Nested classes represent a special type of relationship that is it can access all the
members (data members and methods) of outer class including private.
• Nested classes are used to develop more readable and maintainable code because it
logically groups classes and interfaces in one place only.
• Code Optimization: It requires less code to write.

Static Nested Class

• If the nested class i.e the class defined within another class, has static modifier applied in
it, then it is called as static nested class.
• JAVA static nested classes are declared by using the “static” keyword before class at the
time of class definition.

public class staticInner Output:


{
static int number=25; The number is 25
static class Innerclass
{
void printmsg ()
{
System.out.println ("The number is "+number);}
}
public static void main(String args[] )
{
staticInner.Innerclass object=new staticInner.Innerclass();
object.printmsg();
}
}

17
Inner Class or Member Inner Class:
The most important type of nested class is the inner class. An inner class is a non-static nested
class. It has access to all of the variables and methods of its outer class and may refer to them
directly in the same way that other non-static members of the outer class do.

Following properties can be noted about Inner classes:


▪ The outer class (the class containing the inner class) can instantiate as many
number of inner class objects as it wishes, inside it’s code.
▪ If the inner class is public & the containing class as well, then code in some other
unrelated class can as well create an instance of the inner class.

class OuterClass class Outer


{ {
int outer_x = 121; public void display()
void msg() {
{ Inner in=new Inner();
InnerClass inner = new InnerClass(); in.show();
inner.display(); }
} class Inner
// this is an inner class {
class InnerClass public void show()
{ {
void display() { System.out.println("Inside inner class");
System.out.println("display: outer_x = " + outer_x); }
} }
} }
} class Test
class InnerClassDemo {
{ public static void main(String[] args)
public static void main(String args[]) { {
OuterClass outer = new OuterClass(); Outer ot=new Outer();
outer.msg(); ot.display();
}} }}
Output Output:
Display:outer_x=121 Inside inner class

Method local Inner class

• In Java, we can write a class within a method and this will be a local type. Like local
variables, the scope of the inner class is restricted within the method.
• A method-local inner class can be instantiated only within the method where the inner
class is defined. The following program shows how to use a method-local inner class.

18
class OuterclassTest { class Outer
// instance method of the outer class {
void my_Method() { int count;
int num = 21; public void display()
class MethodInnerClass { // class inside method {
public void print() { for(int i=0;i<5;i++)
System.out.println("This is method inner class {
"+num); class Inner //Inner class defined inside
} for loop
} // end of inner class {
MethodInnerClass inner = new public void show()
MethodInnerClass(); {
inner.print(); System.out.println("Inside inner
} "+(count++));
public static void main(String args[]) { }
OuterclassTest outer = new OuterclassTest(); }
outer.my_Method(); Inner in=new Inner();
}} in.show();
Output: } }}
This is method inner class 21 class Test
{
Output: public static void main(String[] args)
{
Inside inner 0
Inside inner 1
Outer ot=new Outer();
Inside inner 2 ot.display();
Inside inner 3 }}
Inside inner 4

Anonymous Inner Class


An inner class declared without a class name is known as an anonymous inner class. In case of
anonymous inner classes, we declare and instantiate them at the same time. Generally, they
are used whenever you need to override the method of a class or an interface. The syntax of an
anonymous inner class is as follows ?

Syntax:
AnonymousInner an_inner = new AnonymousInner() {
public void my_method() {
........
........
}
};

19
abstract class AnonymousInner Output:
{
This is an example of
public abstract void message();
anonymous inner class
}
public class OuterClass
{
public static void main(String args[]) {
AnonymousInner inner = new AnonymousInner() {
public void message() {
System.out.println("This is an example of anonymous inner class");
}
};
inner.message();
}}

Type Description

Member Inner Class A class created within class and outside method.

Local Inner Class A class created within method.

A class created for implementing interface or extending class.


Anonymous Inner Class
Its name is decided by the java compiler.

Static Nested Class A static class created within class.

Final Class and Method in JAVA:

The final keyword in java is used to restrict the user. It is used to make a variable as a
constant, Restrict method overriding, Restrict inheritance. It is used at variable level,
method level and class level. In java language final keyword can be used in following way.

20
Examples of JAVA final variable
public class Circle Output:
{
3.14
public static final double PI=3.14159;
public static void main(String[] args)
{
System.out.println(PI);
}}

Example of Java final method:

class Bike{ Output:


final void run() Compile Time Error
{System.out.println("running");}
} Because as run method
class Honda extends Bike declared as final we cannot
{ Override the run method.
void run()
{System.out.println("running safely with 100kmph");} Final method here prevents
public static void main(String args[]){ Method overriding.
Honda honda= new Honda();
honda.run(); } }

Example of final class:


final class Bike Output:
{}
Compile Time Error
class Honda1 extends Bike
{ As Final class cannot be
void run(){System.out.println("running safely with 100kmph");} inherited
public static void main(String args[]){
Honda1 honda= new Honda1();
honda.run();
}

Q) Can we declare a constructor final?


No, because constructor is never inherited.

What is blank or uninitialized final variable?


A final variable that is not initialized at the time of declaration is known as blank final variable.
21
If you want to create a variable that is initialized at the time of creating object and once initialized
may not be changed, it is useful.

Que) Can we initialize blank final variable?

Yes, but only in constructor. For example:

class Bike10{
final int speedlimit;//blank final variable

Bike10(){
speedlimit=70;
System.out.println(speedlimit);
}
public static void main(String args[]){
new Bike10();
}
}
static blank final variable
A static final variable that is not initialized at the time of declaration is known as static blank final
variable. It can be initialized only in static block.

Example of static blank final variable


class A{
static final int data;//static blank final variable
static
{ data=50;}
public static void main(String args[]){
System.out.println(A.data);
}
}
Passing Arguments by Value and by Reference

• Pass-by-value means that the actual value of the variable is passed.


• Pass-by-reference means the memory location is passed where the value of the
variable is stored.

22
Java Pass By Value or Call by value

public class Callbyvalue Output:


{
Before call-by-value:10
int a = 10;
void call(int a) After call-by-value:10
{
Here we have initialized a variable ‘a’
a = a+10;
with some value and used the pass-by-
} value technique to show how the value
public static void main(String[] args) of the variable remains unchanged.
{
Callbyvalue eg = new Callbyvalue();
System.out.println("Before call-by-value: " + eg.a);
eg.call(50510);
System.out.println("After call-by-value: " + eg.a);
}}

Java Passing Object: Pass by Reference Example

public class CallbyRef{ Output:


/*
Before call-by-reference: 10
* The original value of 'a' will be changed as we are trying
* to pass the objects. Objects are passed by reference. After call-by-reference: 20
*/
int a = 10;
void call(CallbyRef eg) {
eg.a = eg.a+10;
}
public static void main(String[] args) {
CallbyRef eg = new CallbyRef();
System.out.println("Before call-by-reference: " + eg.a);
// passing the object as a value using pass-by-reference
eg.call(eg);
System.out.println("After call-by-reference: " + eg.a);
}}

23
What is this Keyword in Java?
• this keyword in Java is a reference variable that refers to the current object of a method
or a constructor.
• The main purpose of using this keyword in Java is to remove the confusion between
class attributes and parameters that have same names.

public class Main { class Main {


int x; int age;
// Constructor with a parameter Main(int age){
public Main(int x) { this.age = age;
this.x = x; }
} public static void main(String[] args) {
// Call the constructor Main obj = new Main(8);
public static void main(String[] args) { System.out.println("obj.age = " + obj.age);
Main myObj = new Main(5); }
System.out.println("Value of x = " + myObj.x); }
}
} Output:
Output: Obj.age=8

Value of x=8

Methods:

Introduction, Defining Methods, Overloaded Methods, Overloaded Constructor Methods,


Class Objects as Parameters in Methods, Access Control, Recursive Methods, Nesting of
Methods, Overriding Methods, Attributes Final and Static.

Method:

• A method is a block of code which only runs when it is called.


• You can pass data, known as parameters, into a method.
• Methods are used to perform certain actions, and they are also known as functions.

Why use methods? To reuse code: define the code once, and use it many times.

In Java, there are two types of methods:

• User-defined Methods: We can create our own method based on our requirements.

• Standard Library Methods: These are built-in methods in Java that are available to use.

24
Declaring a Java Method

The syntax to declare a method is:

returnType methodName() {

// method body

Here,

returnType - It specifies what type of value a method returns For example if a method has
an int return type then it returns an integer value.

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

methodName - It is an identifier that is used to refer to the particular method in a program.

method body - It includes the programming statements that are used to perform some tasks.
The method body is enclosed inside the curly braces { }.

Example:

public class Main { public class Main {


static void myMethod() {
static void myMethod() System.out.println("I just got executed!");
{ }
System.out.println("I just got executed!");
} public static void main(String[] args) {
myMethod();
public static void main(String[] args) { myMethod();
myMethod(); myMethod();
} }
} }Output:
Output: I just got executed!
I just got executed! I just got executed!
I just got executed!

Java Method Return Type


A Java method may or may not return a value to the function call. We use the return
statement to return any value. For example,

int addNumbers()

{ return sum ;

25
class Main {
// create a method
public static int square(int num) {
return num * num; // return statement
}
public static void main(String[] args) {
int result;
// store returned value to result
result = square(10); // call the method
System.out.println("Squared value of 10 is: " +
result);
}}
Output:
Square value of 10 is 100

Method Parameters in Java


A method parameter is a value accepted by the method. As mentioned earlier, a method can

also have any number of parameters. For example,

// method with two parameters


int addNumbers(int a, int b) {
// code
}
// method with no parameter
int addNumbers(){
// code
}

Standard Library Methods


The standard library methods are built-in methods in Java that are readily available for use.

These standard libraries come along with the Java Class Library (JCL) in a Java archive (*.jar)

file with JVM and JRE.

For example,
• print() is a method of java.io.PrintStream. The print("...") method prints the string inside

quotation marks.
• sqrt() is a method of Math class. It returns the square root of a number.

26
What is Method Overloading
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.

If a class has multiple methods having same name but different in parameters, it is
known as Method Overloading.
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

Method Overloading: changing no. of arguments

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

class OverloadingExample Output:


{
23
public static void main(String[] args)
{ 39
System.out.println(AdderClass.addition(12,11));
System.out.println(AdderClass.addition(11,15,13));
}
}
class AdderClass
{
static int addition(int a,int b){return a+b;}
static int addition(int a,int b,int c){return
a+b+c;}

27
Method Overloading: changing data type of arguments.

class OverloadingExample Output:


{
public static void main(String[] args) 23
{
26.9
System.out.println(AdderClass.addition(11,12));
System.out.println(AdderClass.addition(11.3,15.6));
}
}
class AdderClass
{
static int addition(int a, int b){
return a+b;
}
static double addition(double a, double b){
return a+b;
}

Can we overload java main() method?

Yes, by method overloading. You can have any number of main methods in a class by method
overloading. But JVM calls main() method which receives string array as arguments only. Let's
see the simple example:

class MainMethodOverloading Output:


{
public static void main() main with String[]
{
System.out.println("main without args");
}
public static void main(String[] args)
{
System.out.println("main with String[]");
}
public static void main(String args)
{
System.out.println("main with String");
}

28
class Add
{
int a;
int b;
Add(int x,int y)// parametrized constructor
{
a=x;
b=y;
}
void sum(Add A1) // object 'A1' passed as parameter in function 'sum'
{
int sum1=A1.a+A1.b;
System.out.println("Sum of a and b :"+sum1);
}
}
public class classExAdd
{
public static void main(String arg[])
{
Add A=new Add(5,8); /* Calls the parametrized constructor with set of parameters*/
A.sum(A);
}
}

Output:
Sum of a and b is 13

Passing Object as Parameter in Constructor


class Add
{
private int a,b;

Add(Add A)
{
a=A.a;
b=A.b;
}

Add(int x,int y)
{
a=x;
b=y;
}

29
void sum()
{
int sum1=a+b;
System.out.println("Sum of a and b :"+sum1);
}}
class ExAddcons
{
public static void main(String arg[])
{
Add A=new Add(15,8);
Add A1=new Add(A);
A1.sum();
}
}
Output:
Sum of a and b is 23

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


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

class Vehicle
{ void run(){System.out.println("Vehicle is running");} //defining a method

class Bike2 extends Vehicle{ //Creating a child 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
30
Can we override static method?
No, a static method cannot be overridden. It can be proved by runtime polymorphism, so we will
learn it later.

Can we override java main method?


No, because the main is a static method.

Difference Between Compile Time and Run Time Polymorphism


Compile Time Polymorphism Runtime Polymorphism
Method Overloading Method Overriding

It is also known as static polymorphism, early It is also known as dynamic polymorphism, late
binding, or overloading binding, or overriding

It is executed at the compile time It is executed at the run time

The method is not called with the help of a


The method is called with the help of a compiler
compiler

The program’s execution is fast as it involves the The program’s execution is slow as it does not
use of a compiler involve a compiler

It is achieved by function overloading and operator It is achieved by virtual overloading and


overloading pointers

Compile-time polymorphism tends to be less Run time polymorphism tends to be more


flexible as all commands are operated at the flexible as all commands are executed at the
compile time. run time

31
Factorial Number
public class RecursionExample3 { factorial(5)
static int factorial(int n){ factorial(4)
if (n == 1) factorial(3)
return 1;
factorial(2)
else
factorial(1)
return(n * factorial(n-1));
return 1
}
return 2*1 = 2
public static void main(String[] args) {
return 3*2 = 6
System.out.println("Factorial of 5 is: "+factorial(5));
} return 4*6 = 24

} return 5*24 = 120

Fibonacci Series

public class RecursionExample4 {


static int n1=0,n2=1,n3=0;
static void printFibo(int count){
if(count>0){
n3 = n1 + n2;
n1 = n2;
n2 = n3;
System.out.print(" "+n3);
printFibo(count-1);
}
}
public static void main(String[] args) {
int count=15;
System.out.print(n1+" "+n2);//printing 0 and 1
printFibo(count-2);//n-2 because 2 numbers are already printed
}
}
Output:
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

32
Method within Method or Nesting of Methods in JAVA:

class demo class test


{ {
private int m, n; int a,b;
demo(int x, int y) test(int p, int q)
{ {
m = x; a=p;
n = y; b=q;
} }
int largest() { int greatest()
if (m > n) {
return m; if(a>=b)
else return(a);
return n; else
} return(b);
void display() }
{ void display()
int large=largest(); {
System.out.println("The Greatest Nu int great=greatest();
mber is : "+large); System.out.println("The Greatest Value="+great);
} }
} }
public class nested_method class temp
{ {
public static void main(String args[]) { public static void main(String args[])
demo o =new demo(10,20); {
o.display(); test t1=new test(25,24);
} t1.display();
} }
Output: }
The Greatest number is 20 Output:
The Greatest value 25

Final Keyword in JAVA:

The final keyword in java is used to restrict the user. It is used to make a variable as a constant,
restrict method overriding, Restrict inheritance. It is used at variable level, method level and
class level.
In java language final keyword can be used in following way.

1. Final at variable level


2. Final at method level
3. Final at class level
33
Examples of final variable
Program:

public class Circle


{
public static final double PI=3.14159;

public static void main(String[] args)


{
System.out.println(PI);
}
}
Output:
3.14159

final method
• When a method is declared with final keyword, it is called a final method.
• A final method cannot be overridden. Which means even though a sub class can
call the final method of parent class without any issues but it cannot override it.

class ClassP class FinalDemo {


{ // create a final method
final void demo() public final void display() {
{ System.out.println("This is a final method.");
System.out.println("ClassP Class Method"); }
} }
} class Main extends FinalDemo {
class ClassC extends ClassP // try to override final method
{ public final void display() {
void demo() System.out.println("The final method is
{ overridden.");
System.out.println("ClassC Class Method"); }
} public static void main(String[] args) {
public static void main(String args[]){ Main obj = new Main();
ClassC obj= new ClassC(); obj.display();
obj.demo(); }
}} }

C:\Users\ClassC.java:8: error: demo() in ClassC cannot override demo() in ClassP


void demo(){
^
overridden method is final 1 error

34
Java final Class
A class declaration with word-final is known as the final class. Final Class in Java can not be
inherited & can not be extended by other classes. A final class can extend other classes; It can
be a subclass but not a superclass.

final class FinalClass { final class ClassP{


public void display() { }
System.out.println("This is a final method."); class ClassC extends ClassP{
} void demo(){
} System.out.println("My Method");
// try to extend the final class }
class Main extends FinalClass { public static void main(String args[]){
public void display() { ClassC obj= new ClassC();
System.out.println("The final method is obj.demo();
overridden."); }
} }
public static void main(String[] args) { Output:
Main obj = new Main(); cannot inherit from final ClassP
obj.display();
class ClassC extends ClassP{
}
} ^
Output:

cannot inherit from final FinalClass


class Main extends FinalClass {

static keyword in JAVA:

• The static keyword is used in java mainly for memory management.


• It is used with variables, methods, blocks and nested class.
• It is a keyword that are used for share the same variable or method of a given class.
• This is used for a constant variable or a method that is the same for every instance
of a class.
• The main method of a class is generally labeled static.

In java language static keyword can be used for following

• variable (also known as a class variable)


• method (also known as a class method)
• block
• nested class

35
Static Variable in JAVA:

If we declare any instance variable with a static modifier, it is known as static variable in java.
A static variable is also known as class variable in java. It stores the value for a variable in a
common memory location.

class Test { public class Student


// static variable {
static int max = 10; static int id = 20;
} public static void main(String[] args)
public class Main { {
public static void main(String[] args) { Student s = new Student();
System.out.println("max + 1 = " + (Test.max + 1)); int x = s.id; // Print on the console.
} System.out.println(x);
System.out.println(Student.id);
} }
}
Output: 10 Output: 20 20

36

You might also like