UNIT-3 Java
UNIT-3 Java
UNIT-3
Java Classes
A class in Java is a set of objects which shares common characteristics/ behavior and common
properties/ attributes. It is a user-defined blueprint or prototype from which objects are created. For
1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects
are created.
Data member
Method
Constructor
Nested Class
Interface
data member;
method;
constructor;
nested class;
interface;
class Student {
int id;
String name;
// creating an object of
// Student
System.out.println(s1.id);
System.out.println(s1.name);
Output
null
java Objects
An object in Java is a basic unit of Object-Oriented Programming and represents real-life entities.
Objects are the instances of a class that are created to use the attributes and methods of a class. A
typical Java program creates many objects, which as you know, interact by invoking methods. An
object consists of :
2. Behavior : It is represented by the methods of an object. It also reflects the response of an object
3. Identity : It gives a unique name to an object and enables one object to interact with other
objects.
Class Object
declared. created.
Class Object
Java Variables
A variable is a container which holds the value while the Java program is executed. A variable is assigned
Variable is a name of memory location. There are three types of variables in java: local, instance and
static.
Types of Variables
o local variable
o instance variable
o static variable
1) Local Variable
A variable declared inside the body of the method is called local variable. You can use this variable only
within that method and the other methods in the class aren't even aware that the variable exists.
2) Instance Variable
A variable declared inside the class but outside the body of the method, is called an instance variable. It
It is called an instance variable because its value is instance-specific and is not shared among instances.
3) Static variable
A variable that is declared as static is called a static variable. It cannot be local. You can create a single
copy of the static variable and share it among all the instances of the class. Memory allocation for static
variables happens only once when the class is loaded in the memory.
public class A
void method()
}//end of class
Java Methods
The method in Java or Methods of Java is a collection of statements that perform some specific tasks
and return the result to the caller. A Java method can perform some specific tasks without returning
anything. Java Methods allows us to reuse the code without retyping the code. In Java, every method
must be part of some class that is different from languages like C, C++, and Python.
Syntax of Method:
//body
Advantage of Method:
Code Reusability
Code Optimization
Method Declaration
1. Modifier: It defines the access type of the method i.e. from where it can be accessed in your
protected: It is accessible within the class in which it is defined and in its subclasses.
default: It is declared/defined without using any modifier. It is accessible within the same class
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
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
void show()
System.out.println("Welcome to javaTpoint");
obj.show();
Output:
Welcome to javaTpoint
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
Syntax:
Or
In the above statement, forName() is a static method of Class 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
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
void show()
try
obj.show();
catch (ClassNotFoundException e)
e.printStackTrace();
catch (InstantiationException e)
e.printStackTrace();
catch (IllegalAccessException e)
e.printStackTrace();
Output:
Constructors in Java
In Java, a constructor is a block of codes similar to the method. It is called when an instance of
the class is created. At the time of calling constructor, memory for the object is allocated in the memory.
Every time an object is created using the new() keyword, at least one constructor is called.
It calls a default constructor if there is no constructor available in the class. In such case, Java compiler
2. Parameterized constructor
<class_name>(){}
In this example, we are creating the no-arg constructor in the Bike class. It will be invoked at the time of object creation.
class Bike1{
Bike1(){System.out.println("Bike is created");}
//main method
Output:
Bike is created
In this example, we have created the constructor of Student class that have two parameters. We can
class Student4{
int id;
String name;
id = i;
name = n;
s1.display();
s2.display();
o/p
111 Karan
222 Aryan
If a class has multiple methods having same name but different in parameters, it is known as Method
Overloading.
If we have to perform only one operation, having same name of the methods increases the readability of
the program.
Suppose you have to perform addition of the given numbers but there can be any number of arguments,
if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters
then it may be difficult for you as well as other programmers to understand the behavior of the method
// overloading in Java
return (x + y + z);
// parameters
return (x + y);
// Driver code
System.out.println(s.sum(10, 20));
System.out.println(s.sum(10.5, 20.5));
Output
30
60
31.0
Static Members
Variables and methods declared using keyword static are called static members of a class. You know
that non-static variables and methods belong to instance. But static members (variables, methods)
belong to class. Static members are not part of any instance of the class. Static members can be
accessed using class name directly, in other words, there is no need to create instance of the class
#Static Variables
#Static Methods
Static Variables
Static variables are also called class variables because they can be accessed using class name, whereas,
non static variables are called instance variables and can be accessed using instance reference only.
Static variables occupy single location in the memory. These can also be accessed using instance
reference.
These are accessible in both static and non-static methods, even non-static methods can change their
values.
While declaration, there is no need to initialize the static variables explicitly because they take default
Let us look at a reason for using one. Suppose you want to keep record about the number of running
Static methods are also called class methods. A static method belongs to class, it can be used with class
Static methods can use static variables only, whereas non-static methods can use both instance
Generally, static methods are used to perform some common tasks for all objects of a class. For
example, a method returns a random number. It does not matters which instance use this method, it
will always behave exactly in this way. In other words, static methods are used when the behavior of a
Implementation:
The following program uses a static counter variable and static method showCount() method to track
class Student
Student()
Output:
Number of students : 2
Number of students : 4
In Java, methods and variables that are defined within a class can only be accessed by creating an
instance of that class or by using the class name if the methods are static. The dot operator is used to
access methods and variables within a class. However, there is an exception to this rule: a method can
also be called by another method using the class name, but only if both methods are present in the
same class. Efficient code organization and simplified method calls within a class are possible through
nesting of methods. Understanding how methods can call other methods within the same class is an
Syntax:
class Main
method1(){
// statements
method2()
// statements
method1();
method3()
// statements
method2();
Example 1:
The program takes input for the length, breadth, and height of a cuboid. The volume method is called
first, which in turn calls the area method. The area method then calls the perimeter method. By invoking
a series of methods, the output for the cuboid can be obtained for its perimeter, area, and volume.
Filename: NestingMethodsExample1.java
import java.util.Scanner;
int p = 4 * (a + y);
return p;
// Calculating area
int r = a * y;
return r;
// Calculating volume
int v = a * y * h;
return v;
int a = scanner.nextInt();
int y = scanner.nextInt();
int h = scanner.nextInt();
// Printing volume
Output:
Perimeter: 224
Area: 768
Volume: 14592
Final Method
The final method in Java is used as a non-access modifier applicable only to a variable, a method, or
1. Variable
2. Method
3. Class
When a variable is declared with the final keyword, its value can’t be changed, essentially,
a constant. This also means that you must initialize a final variable.
If the final variable is a reference, this means that the variable cannot be re-bound to
reference another object, but the internal state of the object pointed by that reference variable can
be changed i.e. you can add or remove elements from the final array or final collection.
It is good practice to represent final variables in all uppercase, using underscore to separate words.
Example:
When a class is declared with the final keyword in Java, it is called a final class. A final class cannot
be extended(inherited).
One is definitely to prevent inheritance, as final classes cannot be extended. For example, all Wrapper
Classes like Integer, Float, etc. are final classes. We can not extend them.
final class A
class B extends A
When a method is declared with final keyword, it is called a final method in Java. A final method
cannot be overridden.
The Object class does this—a number of its methods are final. We must declare methods with the
final keyword for which we are required to follow the same implementation throughout all the
derived classes.
class A
class B extends A
void m1()
System.out.println("Illegal!");