0% found this document useful (0 votes)
4 views30 pages

Java Unit 2

This document covers the fundamentals of classes, objects, and methods in Java, detailing their definitions, declarations, and various modifiers. It explains the characteristics of objects, different ways to create them, and the significance of access control for class members. Additionally, it provides examples and syntax for implementing these concepts in Java programming.

Uploaded by

buppalaiah.svist
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 views30 pages

Java Unit 2

This document covers the fundamentals of classes, objects, and methods in Java, detailing their definitions, declarations, and various modifiers. It explains the characteristics of objects, different ways to create them, and the significance of access control for class members. Additionally, it provides examples and syntax for implementing these concepts in Java programming.

Uploaded by

buppalaiah.svist
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/ 30

UNIT II

CLASSES, OBJECTS AND METHODS

2.1 Classes and Objects in Java:


2.1.1 Classes and Objects: Introduction
2.1.2 Class Declaration and Modifiers
2.1.3 Class Members
2.1.4 Declaration of Class Objects
2.1.5 Assigning One Object to Another
2.1.6 Access Control for Class Members
2.1.7 Accessing Private Members of Class
2.1.8 Constructor Methods for Class
2.1.9 Overloaded Constructor Methods
2.1.10 Nested Classes
2.1.11 Final Class and Methods
2.1.12 Passing Arguments by Value and by Reference
2.1.13 Keyword this.

2.2 Methods in Java:


2.2.1 Introduction
2.2.2 Defining Methods
2.2.3 Overloaded Methods
2.2.4 Overloaded Constructor Methods
2.2.5 Class Objects as Parameters in Methods
2.2.6 Access Control
2.2.7 Recursive Methods
2.2.8 Nesting of Methods
2.2.9 Overriding Methods
2.2.10 Attributes Final and Static.

JAVA PROGRAMMING 1 KKVPRASAD@CSE


2.1 CLASSES AND OBJECTS IN JAVA

2.1.1 CLASSES AND OBJECTS: INTRODUCTION

Class:
A class in JAVA is the building block that leads to Object-Oriented programming. It is a user-
defined data type, which holds its own data members and member functions, which can be accessed and
used by creating an instance of that class. A Java class is like a blueprint for an object.

For Example:
Consider the Class of Cars. There may be many cars with different names and brand but all of
them will share some common properties like all of them will have 4 wheels, Speed Limit, Mileage
range etc. So here, Car is the class and wheels, speed limits, mileage are their properties.

 A Class is a user defined data-type which has data members and member functions.
 Data members are the data variables and member functions are the functions used to
manipulate these variables and together these data members and member functions defines
the properties andbehavior of the objects in a Class.
 In the above example of class Car, the data member will be speed limit, mileage etc and
member functions can be apply brakes, increase speed etc.
 Create a class called "MyClass":
public class MyClass {// The class
int myNum; // Attribute (int variable)
string myString; // Attribute (string variable)
};
Object In Java :
An entity that has state and behavior is known as an object e.g., chair, bike, marker, pen, table, car,
etc. It can be physical or logical (tangible and intangible).
An object has three characteristics:
 State: represents the data (value) of an object.
 Behavior: represents the 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.
The object is a basic building block of an OOPs language. In Java, we cannot execute any program
without creating an object. There is various way to create an object in Java
Java provides five ways to create an object.
 Using new Keyword
 Using clone() method
 Using newInstance() method of the Class class
 Using newInstance() method of the Constructor class
 Using Deserialization

2.1.2 CLASS DECLARATION AND MODIFIERS

Syntax to declare a class. class className {


//Body of the class
}
JAVA PROGRAMMING 2 KKVPRASAD@CSE
You can declare a class by writing the name of the next to the class keyword, followed by the flower
braces. Within these, you need to define the body (contents) of the class i.e. fields and methods.
To make the class accessible to all (classes) you need to make it public.
public class MyClass {
//contents of the class (fields and methods)
}
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:
 Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
 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.
 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.
 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.

There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient,
etc. Here, we are going to learn the access modifiers only.

2.1.3 CLASS MEMBERS

The class members are declared in the body of a class. These may comprise fields (variables in a
class). methods, nested classes, and interfaces. The members of a class comprise the members declared
in the class as well as the members inherited from a super class. The scope of all the members extends to
the entire class body.
The fields comprise two types of variables

1. Non Static variables : These include instance and local variables and vanes in scope and value.
(a) Instance variables: These variables are individual to an object and an object keeps a
copy of these variables in its memory.
(b) Local variables: These are local in scope and not accessible outside their scope.
2. Class variables ( Static Variables) : These variables are also qualified as static variables. The
values of these variables are common to all the objects of the class. The class keeps only one copy of
these variables and all the objects share the same copy. As class variables belong to the whole
class, these are also called class variables.
Example:
class CustomerId
{
static int count=0; // staticvariable
int id; // instancevariable
CustomerId() // Constructor
{
count++;
JAVA PROGRAMMING 3 KKVPRASAD@CSE
id = count ;
}
int getId() // Method
{
return id;
}
int localVar()
{
int a=10; //Local variable
return a;
}
} class
Application
{ public static void main(String[]args)
{
CustomerId obj = new CustomerId();
System.out.println("Customer Id = " + obj.getId()); System.out.println("Local
Variable = " + obj.localVar());
}
}

Output:
Customer Id = 1
Local Variable = 10

2.1.4 DECLARATION OF CLASS OBJECTS

The object is a basic building block of an OOPs language. In Java, we cannot execute any program
without creating an object. There is various way to create an object in Java that we will discuss in this
section, and also learn how to create an object in Java.
Java provides five ways to create an object.
 Using new Keyword
 Using clone() method
 Using newInstance() method of the Class class
 Using newInstance() method of the Constructor class
 Using Deserialization

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();
CreateObjectExample1.java
public class CreateObjectExample1
{
void show()
JAVA PROGRAMMING 4 KKVPRASAD@CSE
{
System.out.println("Welcome to Java Programming");
}
public static void main(String[] args)
{
//creating an object using new keyword
CreateObjectExample1 obj = new CreateObjectExample1();
//invoking method using the object
obj.show();
}
}
Output:
Welcome to Java Programming

Using clone() Method

The clone() method is the method of Object class. It creates a copy of an object and returns the same
copy. The JVM creates a new object when the clone() method is invoked. It copies all the content of the
previously created object into new one object. Note that it does not call any constructor.
We must implement the Cloneable interface while using the clone() method. The method
throws CloneNotSupportedException exception if the object's class does not support the Cloneable interface.
The subclasses that override the clone() method can throw an exception if an instance cannot be cloned.
Syntax:
ClassName newobject = (ClassName) oldobject.clone();

CreateObjectExample3.java
public class CreateObjectExample3 implements Cloneable
{
@Override
protected Object clone() throws CloneNotSupportedException
{
//invokes the clone() method of the super class
return super.clone();
}
String str = "New Object Created";
public static void main(String[] args)
{
//creating an object of the class
CreateObjectExample3 obj1 = new CreateObjectExample3();
//try catch block to catch the exception thrown by the method
try
{
//creating a new object of the obj1 suing the clone() method
CreateObjectExample3 obj2 = (CreateObjectExample3) obj1.clone();
System.out.println(obj2.str);
}
catch (CloneNotSupportedException e)
{
e.printStackTrace();
} } }
Output:
New Object Created

JAVA PROGRAMMING 5 KKVPRASAD@CSE


Using newInstance() Method of Class class

The newInstance() method of the Class class is also used to create an object. It calls the default
constructor to create the object. It returns a newly created instance of the class represented by the object. It
internally uses the newInstance() method of the Constructor class.

ClassName object = ClassName.class.newInstance();

In the above statement, forName() is a static method of Class. It parses a parameter className of
type String.
It returns the object for the class with the fully qualified name. It loads the class but does not create
any object.
It throws ClassNotFoundException if the class cannot be loaded and LinkageError
if the linkage fails.
To create the object, we use the newInstance() method of the Class class. It works only when we
know the name of the class and the class has a public default constructor.
In the following program, we have creates a new object using the newInstance() method.
CreateObjectExample4.java

public class CreateObjectExample4


{
void show()
{
System.out.println("A new object created.");
}
public static void main(String[] args)
{
try
{
//creating an instance of Class class
Class cls = Class.forName("CreateObjectExample4");
//creates an instance of the class using the newInstance() method
CreateObjectExample4 obj = (CreateObjectExample4)
cls.newInstance(); //invoking the show() method
obj.show();
}
catch (ClassNotFoundException e)
{
e.printStackTrace();
}
catch (InstantiationException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
}
}
Output:
A new object created.

JAVA PROGRAMMING 6 KKVPRASAD@CSE


Using newInstance() Method of Constructor class

It is similar to the newInstance() method of the Class class. It is known as a reflective way to create
objects. The method is defined in the Constructor class which is the class of java.lang.reflect package. We
can also call the parameterized constructor and private constructor by using the newInstance() method. It is
widely preferred in comparison to newInstance() method of the Class class.
Syntax:
public T newInstance(Object... initargs) throws InstantiationException, IllegalAccessException, IllegalArg
umentException, InvocationTargetException
The method parses an array of Objects as an argument. The values of primitive types wrapped in a
wrapper Object of the appropriate type. It returns a new object created by calling the constructor. It
throws IllegalAccessException, IllegalArgumentException, InstantiationException, InvocationTarget
Exception, ExceptionInInitializerError Exceptions.
We can create an object in the following way:

Constructor<Employee> constructor = Employee.class.getConstructor();


Employee emp3 = constructor.newInstance();

CreateObjectExample5.java

import java.lang.reflect.*;
public class CreateObjectExample5 {
private String str;
CreateObjectExample5()
{ }
public void setName(String str)
{
this.str = str;
}
public static void main(String[] args)
{
try
{
Constructor<CreateObjectExample5> constructor = CreateObjectExample5.class.get
DeclaredConstructor();
CreateObjectExample5 r = constructor.newInstance();
r.setName("JavaTpoint");
System.out.println(r.str);
}
catch (Exception e)
{
e.printStackTrace();
} } }
Output:
JavaTpoint

Using Deserialization
In Java, serialization is the process of converting an object into a sequence of byte-stream. The
reverse process (byte-stream to object) of serialization is called deserialization. The JVM creates a new
object when we serialize or deserialize an object. It does not use constructor to create an object. While using
deserialization, the Serializable interface (marker interface) must be implemented in the class.

JAVA PROGRAMMING 7 KKVPRASAD@CSE


Serialization: The writeObject() method of the ObjectOutputStream class is used to serialize an
object. It sends the object to the output stream.
Syntax:
public final void writeObject(object x) throws IOException
Deserialization: The method readObject() of ObjectInputStream class is used to deserialize an object.
It references objects out of a stream.
public final Object readObject()throws IOException,ClassNotFoundException

2.1.5 ASSIGNING ONE OBJECT TO ANOTHER

Java provides the facility to assign one object to another object


Syntax:
new_Object = old_object;

All the properties of old_object will be copied to new object.


Example:
classFarm
{
double length;
doublewidth;
double area()
{
return length*width;
}
}
public class FarmExel
{
public static void main (String args[])
{
Farm farm1 = new Farm(); //defining an object of Farm
Farm farm2 = new Farm(); //defining new object of Farm
farm1.length = 20.0;
farm1.width = 40.0;
System.out.println("Area of form1= " + farm1.area());
farm2 = farm1; // ObjectAssignment
System.out.println("Area of form2 = " + farm2.area());
}
}
Output:
Area of form1= 800.0 Area of form2 = 800.0

JAVA PROGRAMMING 8 KKVPRASAD@CSE


2.1.6 ACCESS CONTROL FOR CLASS MEMBERS

There are two types of modifiers in Java: access modifiers and non-access modifiers.
The access modifier 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:


 Private: The access level of a private modifier is only within the class. It cannot be accessed from
outside the class.
 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.
 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.
 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.
There are many non-access modifiers, such as static, abstract, synchronized, native, volatile, transient, etc.
Here, we are going to learn the access modifiers only.

1) Private :
The private access modifier is accessible only within the class.
Simple example of private access modifier
In this example, we have created two classes A and Simple. A class contains private data member
and private method. We are accessing these private members from outside the class, so there is a compile-
time error.
class A{
private int data=40;
private void msg(){System.out.println("Hello java");}
}
public class Simple{
public static void main(String args[]){
A obj=new A();
System.out.println(obj.data);//Compile Time Error
obj.msg();//Compile Time Error
} }
2) Default :
If you don't use any modifier, it is treated as default by default. The default modifier is accessible
only within package. It cannot be accessed from outside the package. It provides more accessibility than
private. But, it is more restrictive than protected, and public.
Example of default access modifier
In this example, we have created two packages pack and mypack. We are accessing the A class from
outside its package, since A class is not public, so it cannot be accessed from outside the package.
//save by A.java
package pack;
class A{
void msg(){
System.out.println("Hello");} }
JAVA PROGRAMMING 9 KKVPRASAD@CSE
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();//Compile Time Error
obj.msg();//Compile Time Error
} }
In the above example, the scope of class A and its method msg() is default so it cannot be accessed
from outside the package.

3) Protected :
The protected access modifier is accessible within package and outside the package but through
inheritance only.
The protected access modifier can be applied on the data member, method and constructor. It can't
be applied on the class. It provides more accessibility than the default modifer.
In this example, we have created the two packages pack and mypack. The A class of pack package is
public, so can be accessed from outside the package. But msg method of this package is declared as
protected, so it can be accessed from outside the class only through inheritance.
//save by A.java
package pack;
public class A{
protected void msg(){
System.out.println("Hello");
} }
//save by B.java
package mypack;
import pack.*;
class B extends A{
public static void main(String args[]){
B obj = new B();
obj.msg();
} }
4) Public :
The public access modifier is accessible everywhere. It has the widest scope among all other
modifiers.
Example of public access modifier
//save by A.java
package pack;
public class A{
public void msg(){System.out.println("Hello");}
}
//save by B.java
package mypack;
import pack.*;
class B{
public static void main(String args[]){
A obj = new A();
obj.msg();
} }

JAVA PROGRAMMING 10 KKVPRASAD@CSE


2.1.7 ACCESSING PRIVATE MEMBERS OF CLASS

Example 1: Access private fields using getter and setter methods


class Test {
// private variables
private int age;
private String name;
// initialize age
public void setAge(int age) {
this.age = age;
}
// initialize name
public void setName(String name) {
this.name = name;
}
// access age
public int getAge() {
return this.age;
}
// access name
public String getName() {
return this.name;
}
}
class Main {
public static void main(String[] args) {
// create an object of Test
Test test = new Test();
// set value of private variables
test.setAge(24);
test.setName("Programiz");
// get value of private variables
System.out.println("Age: " + test.getAge());
System.out.println("Name: " + test.getName());
}
}
Output :
Age: 24
Name: Programiz

In the above example, we have private variables named age and name. Here, we are trying to access
the private variables from other class named Main.
We have used the getter and setter method to access the private variables. Here,

 the setter methods setAge() and setName() initializes the private variables
 the getter methods getAge() and getName() returns the value of private variables

JAVA PROGRAMMING 11 KKVPRASAD@CSE


Example 2: Access the private field and method using Reflection
import java.lang.reflect.*;
class Test {
// private variables
private String name;
// private method
private void display() {
System.out.println("The name is " + name);
}
}
class Main {
public static void main(String[] args) {
try {
// create an object of Test
Test test = new Test();
// create an object of the class named Class
Class obj = test.getClass();
// access the private variable
Field field = obj.getDeclaredField("name");
// make private field accessible
field.setAccessible(true);
// set value of field
field.set(test, "Programiz");
// get value of field
// and convert it in string
String value = (String)field.get(test);
System.out.println("Name: " + value);
// access the private method
Method[] methods = obj.getDeclaredMethods();
System.out.println("Method Name: " + methods[0].getName());
int modifier = methods[0].getModifiers();
System.out.println("Access Modifier: " + Modifier.toString(modifier));
}
catch(Exception e) {
e.printStackTrace();
}
}
}
Output:
Name: Programiz
Method Name: display
Access Modifier: private
In this example, we have a private field named name and a private method named display(). Here, we
are using the reflection to access the private fields and methods of the class Test.

JAVA PROGRAMMING 12 KKVPRASAD@CSE


2.1.8 CONSTRUCTOR METHODS FOR CLASS
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.

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

Java Default Constructor

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


Syntax of default constructor:
<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

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.

JAVA PROGRAMMING 13 KKVPRASAD@CSE


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[]){
//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();
}
}
Output:
111 Karan
222 Aryan

2.1.9 OVERLOADED CONSTRUCTOR METHODS


In Java, a constructor is just like a method but without return type. It can also be overloaded like Java
methods.
Constructor overloading in Java is a technique of having more than one constructor with different
parameter lists. They are arranged in a way that each constructor performs a different task. They are
differentiated by the compiler by the number of parameters in the list and their types.

Example of Constructor Overloading


//Java program to overload constructors
class Student5{
int id;
String name;
int age;
//creating two arg constructor
Student5(int i,String n){
id = i;
name = n;
}
//creating three arg constructor
Student5(int i,String n,int a){

JAVA PROGRAMMING 14 KKVPRASAD@CSE


id = i;
name = n;
age=a;
}
void display(){System.out.println(id+" "+name+" "+age);}
public static void main(String args[]){
Student5 s1 = new Student5(111,"Karan");
Student5 s2 = new Student5(222,"Aryan",25);
s1.display();
s2.display();
} }
Output:
111 Karan 0
222 Aryan 25

Difference between constructor and method in Java


There are many differences between constructors and methods. They are given below.

Java Constructor Java Method


A constructor is used to initialize the state of an A method is used to expose the behavior of an
object. object.
A constructor must not have a return type. A method must have a return type.
The constructor is invoked implicitly. The method is invoked explicitly.
The Java compiler provides a default constructor The method is not provided by the compiler in any
if you don't have any constructor in a class. case.
The constructor name must be same as the class The method name may or may not be same as the
name. class name.

2.1.10 NESTED CLASSES


Java inner class or nested class is a class that is declared inside the class or interface. We use inner
classes to logically group classes and interfaces in one place to be more readable and maintainable.
Additionally, it can access all the members of the outer class, including private data members and
methods.
Syntax of Inner class
class Java_Outer_class{
//code
class Java_Inner_class{
//code
} }

Advantage of Java inner classes

There are three advantages of inner classes in Java. They are as follows:
1. Nested classes represent a particular type of relationship that is it can access all the members (data
members and methods) of the outer class, including private.
2. Nested classes are used to develop more readable and maintainable code because it logically
group classes and interfaces in one place only.
3. Code Optimization: It requires less code to write.

JAVA PROGRAMMING 15 KKVPRASAD@CSE


Need of Java Inner class

Sometimes users need to program a class in such a way so that no other class can access it.
Therefore, it would be better if you include it within other classes.
If all the class objects are a part of the outer object then it is easier to nest that class inside the outer
class. That way all the outer class can access all the objects of the inner class.
Writing a class within another is allowed in Java. The class written within is called the nested class, and the
class that holds the inner class is called the outer class. Nested classes are divided into two types −
 Non-static nested classes (Inner Classes) − These are the non-static members of a class.
 Static nested classes − These are the static members of a class.
Following are the types of Nested classes in Java −

Non-static nested classes (Inner Classes)


Inner classes are a security mechanism in Java. We know a class cannot be associated with the
access modifier private, but if we have the class as a member of other class, then the inner class can be
made private. And this is also used to access the private members of a class.

Example
class Outer_Demo {
int num;
// inner class
private class Inner_Demo {
public void print() {
System.out.println("This is an inner class");
}}
// Accessing he inner class from the method within
void display_Inner() {
Inner_Demo inner = new Inner_Demo();
inner.print();
}}
public class My_class {
public static void main(String args[]) {
// Instantiating the outer class
Outer_Demo outer = new Outer_Demo();
// Accessing the display_Inner() method.
outer.display_Inner();
}}
Output : This is an inner class.

JAVA PROGRAMMING 16 KKVPRASAD@CSE


Static Nested Classes
A static inner class is a nested class which is a static member of the outer class. It can be accessed
without instantiating the outer class, using other static members. Just like static members, a static nested
class does not have access to the instance variables and methods of the outer class.

Example
public class Outer {
static class Nested_Demo {
public void my_method() {
System.out.println("This is my nested class");
}}
public static void main(String args[]) {
Outer.Nested_Demo nested = new Outer.Nested_Demo();
nested.my_method();
}}
Output
This is my nested class

2.1.11 FINAL CLASS AND METHODS


The final keyword in java is used to restrict the user. The java final keyword can be used in
manycontext. 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.

Advantages of Final Keyword:


 Stop Value Change
 Stop Method Overriding
 Stop Inheritance
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 speed limit, 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

JAVA PROGRAMMING 17 KKVPRASAD@CSE


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

2.1.12 PASSING ARGUMENTS BY VALUE AND BY REFERENCE


Pass by Value in Java
When we pass only the value part of a variable to a function as an argument, it is referred to as pass
by value. In this case, any change to the value of a parameter in the called method does not affect its value in
the calling method.
As can be seen in the figure below, only the value part of the variable is passed i.e. a copy of the
existing variable is passed instead of passing the origin variable. Hence, any changes done to the value of the
copy will not have any impact on the value of the original variable. Java supports pass-by-value.

JAVA PROGRAMMING 18 KKVPRASAD@CSE


Pass by Reference - Not supported by Java
When reference to the location of a variable is passed to a function as an argument, then it is
called pass by reference. In this case, any changes to the value of a parameter inside the function are
reflected outside as well.
As we can see in the below figure, the memory address of the variable is stored in a pointer, and this
pointer is passed to the function as arguments. In this case, the called function will have access to the
original address of the variable. Thus, if we change the value of the variable inside the method, the change is
reflected outside the method as well.
Java does not support pass-by-reference as it does not have the concept of pointers. But we can
achieve pass-by-reference in Java through the following ways:

How Java Handles Pass by Reference Using Pass by Value


In Java, when we create a variable of class type, the variable holds the reference to the object in the
heap memory. This reference is stored in the stack memory.
Hence, when we pass the variable as an argument to a method, we inherently pass a copy of the
reference to the object in the heap memory. As a result, the method parameter that receives the object refers
to the same object as that referred to by the argument.
Thus, changes to the properties of the object inside the method are reflected outside as well. This
effectively means that objects are passed to methods by use of call-by-reference.
Changes to the properties of an object inside a method affect the original argument as well. However,
if we change the object altogether, then the original object is not changed. Instead a new object is created in
the heap memory and that object is assigned to the copied reference variable passed as argument.

2.1.13 KEYWORD THIS


In Java, this is a reference variable that refers to the current object.

JAVA PROGRAMMING 19 KKVPRASAD@CSE


Usage of Java this keyword
1. this can be used to refer current class instance variable.
2. this can be used to invoke current class method (implicitly)
3. this() can be used to invoke current class constructor.
4. this can be passed as an argument in the method call.
5. this can be passed as argument in the constructor call.
6. this can be used to return the current class instance from the method.
Example
public class Main {
int x;
// Constructor with a parameter
public Main(int x) {
this.x = x;
}
// Call the constructor
public static void main(String[] args) {
Main myObj = new Main(5);
System.out.println("Value of x = " + myObj.x);
}
}
Output : Value of x = 5

The most common use of the this keyword is to eliminate the confusion between class attributes and
parameters with the same name (because a class attribute is shadowed by a method or constructor
parameter). If you omit the keyword in the example above, the output would be "0" instead of "5".

JAVA PROGRAMMING 20 KKVPRASAD@CSE


2.2 METHODS

2.2.1 INTRODUCTION :METHODS


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.
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.

Types of Methods in Java


1. Predefined Method: In Java, predefined methods are the method that is already defined in the
Java class libraries is known as predefined methods. It is also known as the standard library
method or built-in method. We can directly use these methods just by calling them in the program at any
point.
2. User-defined Method: The method written by the user or programmer is known as a user-
defined method. These methods are modified according to the requirement.

2.2.2 DEFINING METHODS


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.

 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.
JAVA PROGRAMMING 21 KKVPRASAD@CSE
 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.

Naming a Method
While defining a method, remember that the method name must be a verb and start with
a lowercase letter. If the method name has more than two words, the first name must be a verb followed by
adjective or noun. In the multi-word method name, the first letter of each word must be in uppercase except
the first word. For example:
Single-word method name: sum(), area()
Multi-word method name: areaOfCircle(), stringComparision()
It is also possible that a method has the same name as another method name in the same class, it is
known as method overloading.

Types of Method
There are two types of methods in Java:
Predefined Method
User-defined Method
Predefined Method
In Java, predefined methods are the method that is already defined in the Java class libraries is
known as predefined methods. It is also known as the standard library method or built-in method. We can
directly use these methods just by calling them in the program at any point. Some pre-defined methods
are length(), equals(), compareTo(), sqrt(), etc.
Demo.java
public class Demo
{
public static void main(String[] args)
{
// using the max() method of Math class
System.out.print("The maximum number is: " + Math.max(9,7));
}
}
Output:
The maximum number is: 9

User-defined Method
The method written by the user or programmer is known as a user-defined method. These methods
are modified according to the requirement.
EvenOdd.java
import java.util.Scanner;
public class EvenOdd
{
public static void main (String args[])
{
//creating Scanner class object
Scanner scan=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
JAVA PROGRAMMING 22 KKVPRASAD@CSE
int num=scan.nextInt();
//method calling
findEvenOdd(num);
}
//user defined method
public static void findEvenOdd(int num)
{
//method body
if(num%2==0)
System.out.println(num+" is even");
else
System.out.println(num+" is odd");
}
}
Output 1:
Enter the number: 12
12 is even
Output 2:
Enter the number: 99
99 is odd

2.2.3 OVERLOADED METHODS


If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
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.
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
By changing number of arguments
By changing the data type

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
JAVA PROGRAMMING 23 KKVPRASAD@CSE
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
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

2.2.4 OVERLOADED CONSTRUCTOR METHODS

In Java, we can overload constructors like methods. The constructor overloading can be defined as
the concept of having more than one constructor with different parameters so that every constructor can
perform a different task.
Example:
public class Student {
int id;
String name;
Student(){
System.out.println("this a default constructor");
}
Student(int i, String n){
id = i;
name = n;
}
public static void main(String[] args) {
Student s = new Student();
System.out.println("\nDefault Constructor values: \n");
System.out.println("Student Id : "+s.id + "\nStudent Name : "+s.name);

JAVA PROGRAMMING 24 KKVPRASAD@CSE


System.out.println("\nParameterized Constructor values: \n");
Student student = new Student(10, "Krishna");
System.out.println("Student Id : "+student.id + "\nStudent Name : "+student.n
ame);
} }
Output:
this a default constructor
Default Constructor values:
Student Id : 0
Student Name : null
Parameterized Constructor values:
Student Id : 10
Student Name : Krishna
In the above example, the Student class constructor is overloaded with two different constructors,
I.e., default and parameterized.

Use of this () in constructor overloading


However, we can use this keyword inside the constructor, which can be used to invoke the other
constructor of the same class.
Consider the following example to understand the use of this keyword in constructor overloading.
public class Student {
//instance variables of the class
int id,passoutYear;
String name,contactNo,collegeName;
Student(String contactNo, String collegeName, int passoutYear){
this.contactNo = contactNo;
this.collegeName = collegeName;
this.passoutYear = passoutYear;
}
Student(int id, String name){
this("9899234455", "IIT Kanpur", 2018);
this.id = id;
this.name = name;
}
public static void main(String[] args) {
//object creation
Student s = new Student(101, "John");
System.out.println("Printing Student Information: \n");
System.out.println("Name: "+s.name+"\nId: "+s.id+"\nContact No.: "+s.conta
ctNo+"\nCollege Name: "+s.contactNo+"\nPassing Year: "+s.passoutYear);
} }
Output:
Printing Student Information:
Name: John
Id: 101
Contact No.: 9899234455
College Name: 9899234455
Passing Year: 2018

JAVA PROGRAMMING 25 KKVPRASAD@CSE


2.2.5 CLASS OBJECTS AS PARAMETERS IN METHODS

In Java we can pass objects as argument. In the following Java example, we a have a class with two
instance variables name and age and a parameterized constructor initializing these variables.
We have a method coypObject() which accepts an object of the current class and initializes the
instance variables with the variables of this object and returns it.
In the main method we are instantiating the Student class and making a copy by passing it as an
argument to the coypObject() method.

import java.util.Scanner;
public class Student {
private String name;
private int age;
public Student(){
}
public Student(String name, int age){
this.name = name;
this.age = age;
}
public Student copyObject(Student std){
this.name = std.name;
this.age = std.age;
return std;
}
public void displayData(){
System.out.println("Name : "+this.name);
System.out.println("Age : "+this.age);
}
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
System.out.println("Enter your name : ");
String name = sc.next();
System.out.println("Enter your age : ");
int age = sc.nextInt();
Student std = new Student(name, age);
System.out.println("Contents of the original object");
std.displayData();
System.out.println("Contents of the copied object");
Student copyOfStd = new Student().copyObject(std);
copyOfStd.displayData();
}
}
Output
Enter your name : Krishna
Enter your age : 20
Contents of the original object
Name : Krishna
Age : 20
Contents of the copied object
Name : Krishna
Age : 20

JAVA PROGRAMMING 26 KKVPRASAD@CSE


2.2.6 ACCESS CONTROL

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 .

Members of JAVA Private Default Protected Public


Class No Yes No Yes
Variable Yes Yes Yes Yes
Method Yes Yes Yes Yes
Constructor Yes Yes Yes Yes
interface No Yes No Yes
Initializer Block NOT ALLOWED

2.2.7 RECURSIVE METHODS

Recursion in java is a process in which a method calls itself continuously. A method in java that calls
itself is called recursive method.
Syntax:
returntype methodname(){
//code to be executed
methodname();//calling same method
}

Java Recursion Example : Factorial Number


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

Working of above program:


factorial(5)
factorial(4)
factorial(3)
factorial(2)
factorial(1)
return 1
return 2*1 = 2
return 3*2 = 6
return 4*6 = 24
return 5*24 = 120
JAVA PROGRAMMING 27 KKVPRASAD@CSE
2.2.8 NESTING OF METHODS

A method can be called by using only its name by another method of the same class that is called
Nesting of Methods. A method of a class can be called only by an object of that class using the dot operator.
So, there is an exception to this. When a method in java calls another method in the same class, it is called
Nesting of methods.
//Nesting of Methods in Java
class demo {
private int m, n;
demo(int x, int y) {
m = x;
n = y;
}
int largest() {
if (m > n)
return m;
else
return n;
}
void display()
{
int large=largest();
System.out.println("The Greatest Number is : "+large);
}
}
public class nested_method {
public static void main(String args[]) {
demo o =new demo(10,20);
o.display();
}
}
Output
The Greatest Number is : 20

2.2.9 OVERRIDING METHODS

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


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

JAVA PROGRAMMING 28 KKVPRASAD@CSE


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.


//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;}
}
//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());
}
}
Output:
SBI Rate of Interest: 8
ICICI Rate of Interest: 7
AXIS Rate of Interest: 9

JAVA PROGRAMMING 29 KKVPRASAD@CSE


2.2.10 ATTRIBUTES FINAL AND STATIC.

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

Java static method


If you apply static keyword with any method, it is known as static method.
 A static method belongs to the class rather than the object of a class.
 A static method can be invoked without the need for creating an instance of a class.
 A static method can access static data member and can change the value of it.
Example of static method
class Student{
int rollno;
String name;
static String college = "ITS";
//static method to change the value of static variable
static void change(){
college = "BBDIT";
}
Student(int r, String n){
rollno = r;
name = n;
}
void display(){System.out.println(rollno+" "+name+" "+college);}
}
//Test class to create and display the values of object
public class TestStaticMethod{
public static void main(String args[]){
Student.change();//calling change method
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
Student s3 = new Student(333,"Sonoo");
s1.display();
s2.display();
s3.display();
}
}
Output: 111 Karan BBDIT
222 Aryan BBDIT
333 Sonoo BBDIT

JAVA PROGRAMMING 30 KKVPRASAD@CSE

You might also like