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

UNIT-3 Java

This document provides an overview of Java classes, objects, variables, methods, constructors, and static members. It explains the properties of classes, the differences between classes and objects, and the types of variables in Java. Additionally, it covers method overloading and the concept of static members, including static variables and methods.
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 views27 pages

UNIT-3 Java

This document provides an overview of Java classes, objects, variables, methods, constructors, and static members. It explains the properties of classes, the differences between classes and objects, and the types of variables in Java. Additionally, it covers method overloading and the concept of static members, including static variables and methods.
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/ 27

1

UNIT-3

Objects and Classes

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

example, Student is a class while a particular student named Ravi is an object.

Properties of Java Classes

1. Class is not a real-world entity. It is just a template or blueprint or prototype from which objects

are created.

2. Class does not occupy memory.

3. Class is a group of variables of different data types and a group of methods.

4. A Class in Java can contain:

 Data member

 Method

 Constructor

 Nested Class

 Interface

Class Declaration in Java

access_modifier class <class_name>

Subject- Java Programming Created by-S.B.Baviskar


2

data member;

method;

constructor;

nested class;

interface;

// Java Program for class example

class Student {

// data member (also instance variable)

int id;

// data member (also instance variable)

String name;

public static void main(String args[])

// creating an object of

// Student

Student s1 = new Student();

System.out.println(s1.id);

System.out.println(s1.name);

Subject- Java Programming Created by-S.B.Baviskar


3

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 :

1. State : It is represented by attributes of an object. It also reflects the properties of an object.

2. Behavior : It is represented by the methods of an object. It also reflects the response of an object

with other objects.

3. Identity : It gives a unique name to an object and enables one object to interact with other

objects.

The differences between class and object in Java are as follows:

Class Object

Class is the blueprint of an object. It is used to


An object is an instance of the class.
create objects.

No memory is allocated when a class is Memory is allocated as soon as an object is

declared. created.

Subject- Java Programming Created by-S.B.Baviskar


4

Class Object

An object is a real-world entity such as a book,


A class is a group of similar objects.
car, etc.

Class is a logical entity. An object is a physical entity.

Objects can be created many times as per


A class can only be declared once.
requirement.

Objects of the class car can be BMW, Mercedes,


An example of class can be a car.
Ferrari, etc.

Java Variables

A variable is a container which holds the value while the Java program is executed. A variable is assigned

with a data type.

Variable is a name of memory location. There are three types of variables in java: local, instance and

static.

Types of Variables

There are three types of variables in Java:

o local variable

o instance variable

Subject- Java Programming Created by-S.B.Baviskar


5

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.

A local variable cannot be defined with "static" keyword.

2) Instance Variable

A variable declared inside the class but outside the body of the method, is called an instance variable. It

is not declared as static.

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.

Example to understand the types of variables in java

public class A

static int m=100;//static variable

void method()

int n=90;//local variable

Subject- Java Programming Created by-S.B.Baviskar


6

public static void main(String args[])

int data=50;//instance variable

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

 A method is like a function i.e. used to expose the behavior of an object.

 It is a set of codes that perform a particular task.

Syntax of Method:

<access_modifier> <return_type> <method_

<access_modifier> <return_type> <method_name>( list_of_parameters)

//body

Advantage of Method:

 Code Reusability

 Code Optimization

Subject- Java Programming Created by-S.B.Baviskar


7

Method Declaration

In general, method declarations have 6 components:

1. Modifier: It defines the access type of the method i.e. from where it can be accessed in your

application. In Java, there 4 types of access specifiers.

 public: It is accessible in all classes in your application.

 protected: It is accessible within the class in which it is defined and in its subclasses.

 private: It is accessible only within the class in which it is defined.

 default: It is declared/defined without using any modifier. It is accessible within the same class

and package within which its class is defined.

How to Create Object in Java

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.

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:

1. ClassName object = new ClassName();

Subject- Java Programming Created by-S.B.Baviskar


8

public class CreateObjectExample1

void show()

System.out.println("Welcome to javaTpoint");

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 javaTpoint

Using newInstance() Method of Class class

Subject- Java Programming Created by-S.B.Baviskar


9

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.

Syntax:

1. public T newInstance() throws InstantiationException, IllegalAccessException

It throws the IllegalAccessException, InstantiationException, ExceptionInInitializerError exceptions.

We can create an object in the following ways:

1. ClassName object = ClassName.class.newInstance();

Or

1. ClassName object = (ClassName) Class.forName("fully qualified name of the class").newInstance();

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

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

Subject- Java Programming Created by-S.B.Baviskar


10

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

Subject- Java Programming Created by-S.B.Baviskar


11

catch (IllegalAccessException e)

e.printStackTrace();

Output:

A new object created.

Constructors in Java

In Java, a constructor is a block of codes similar to the method. It is called when an instance of

the class is created. At the time of calling constructor, memory for the object is allocated in the memory.

It is a special type of method which is used to initialize the object.

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

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

provides a default constructor by default.

Types of Java constructors

There are two types of constructors in Java:

1. Default constructor (no-arg constructor)

Subject- Java Programming Created by-S.B.Baviskar


12

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

Subject- Java Programming Created by-S.B.Baviskar


13

Java Parameterized Constructor

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

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

Subject- Java Programming Created by-S.B.Baviskar


14

s2.display();

o/p

111 Karan

222 Aryan

Method Overloading in Java

If a class has multiple methods having same name but different in parameters, it is known as Method

Overloading.

If we have to perform only one operation, having same name of the methods increases the readability of

the program.

Suppose you have to perform addition of the given numbers but there can be any number of arguments,

if you write the method such as a(int,int) for two parameters, and b(int,int,int) for three parameters

then it may be difficult for you as well as other programmers to understand the behavior of the method

because its name differs.

Subject- Java Programming Created by-S.B.Baviskar


15

// Java program to demonstrate working of method

// overloading in Java

public class Sum {

// Overloaded sum(). This sum takes two int parameters

public int sum(int x, int y) { return (x + y); }

// Overloaded sum(). This sum takes three int parameters

public int sum(int x, int y, int z)

return (x + y + z);

// Overloaded sum(). This sum takes two double

// parameters

public double sum(double x, double y)

return (x + y);

Subject- Java Programming Created by-S.B.Baviskar


16

// Driver code

public static void main(String args[])

Sum s = new Sum();

System.out.println(s.sum(10, 20));

System.out.println(s.sum(10, 20, 30));

System.out.println(s.sum(10.5, 20.5));

Output

30

60

31.0

Subject- Java Programming Created by-S.B.Baviskar


17

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

specifically to use them.

Static members can be of two types:

#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

values like other non-static variables (instance variables).

Now, the question is, why to use static variables?

Let us look at a reason for using one. Suppose you want to keep record about the number of running

Subject- Java Programming Created by-S.B.Baviskar


18

instances of a class. In this situation, it would be better to declare a static variable.

Static Methods/Class Methods

Static methods are also called class methods. A static method belongs to class, it can be used with class

name directly. It is also accessible using instance references.

Static methods can use static variables only, whereas non-static methods can use both instance

variables and static variables.

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

method has no dependency on the values of instance variables.

Implementation:

The following program uses a static counter variable and static method showCount() method to track

the number of running instances of the class student in the memory.

class Student

{ private static int count=0; //static variable

Student()

count++; //increment static variable

Subject- Java Programming Created by-S.B.Baviskar


19

static void showCount() //static method

System.out.println(“Number Of students : “+count);

public class StaticDemo

public static void main(String[] args)

Student s1=new Student();

Student s2=new Student();

Student.showCount(); //calling static method

Student s3=new Student();

Student s4=new Student();

s4.showCount(); //calling static method

Output:

Number of students : 2

Number of students : 4

Subject- Java Programming Created by-S.B.Baviskar


20

Nesting Of Methods in Java

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

important aspect of Java programming.

Syntax:

class Main

method1(){

// statements

method2()

// statements

// calling method1() from method2()

method1();

method3()

Subject- Java Programming Created by-S.B.Baviskar


21

// statements

// calling of method2() from method3()

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;

public class NestingMethodsExample1 {

// Method to calculate the perimeter of a rectangle

int perimeter(int a, int y) {

int p = 4 * (a + y);

return p;

// Method to calculate the area of a rectangle, using the perimeter method

Subject- Java Programming Created by-S.B.Baviskar


22

int area(int a, int y) {

// Calling perimeter method to calculate perimeter

int p = perimeter(a, y);

System.out.println("Perimeter: " + p);

// Calculating area

int r = a * y;

return r;

// Method to calculate the volume of a cuboid, using the area method

int volume(int a, int y, int h) {

// Calling area method to calculate area

int r = area(a, y);

system.out.println("Area: " + r);

// Calculating volume

int v = a * y * h;

return v;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

// Getting input from user

Subject- Java Programming Created by-S.B.Baviskar


23

System.out.print("Length of the rectangle: ");

int a = scanner.nextInt();

System.out.print("Breadth of the rectangle: ");

int y = scanner.nextInt();

System.out.print("Height of the cuboid: ");

int h = scanner.nextInt();

// Creating object of NestingMethodsExample class

NestingMethodsExample obj = new NestingMethodsExample();

// Calling volume method to calculate volume

int volume = obj.volume(a, y, h);

// Printing volume

System.out.println("Volume: " + volume);

Output:

Length of the rectangle: 24

Breadth of the rectangle: 32

Height of the cuboid: 19

Perimeter: 224

Subject- Java Programming Created by-S.B.Baviskar


24

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

a class. It is used to restrict a user in Java.

The following are different contexts where the final is used:

1. Variable

2. Method

3. Class

Java Final Variable

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:

public class ConstantExample {

public static void main(String[] args) {

Subject- Java Programming Created by-S.B.Baviskar


25

// Define a constant variable PI

final double PI = 3.14159;

// Print the value of PI

System.out.println("Value of PI: " + PI);

java Final classes

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

// methods and fields

// The following class is illegal

class B extends A

// COMPILE-ERROR! Can't subclass A

Subject- Java Programming Created by-S.B.Baviskar


26

Java Final Method

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.

Illustration: Final keyword with a method

class A

final void m1()

System.out.println("This is a final method.");

class B extends A

void m1()

// Compile-error! We can not override

System.out.println("Illegal!");

Subject- Java Programming Created by-S.B.Baviskar


27

Subject- Java Programming Created by-S.B.Baviskar

You might also like