KEMBAR78
Intro To Java Classes | PDF | Programming | Constructor (Object Oriented Programming)
0% found this document useful (0 votes)
20 views18 pages

Intro To Java Classes

Class fundamentals, declaring class, creating objects, introducing methods: method declaration, overloading, using objects as parameters, recursion, Constructors, this keyword, garbage collection, the finalization.

Uploaded by

ankkumar835
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)
20 views18 pages

Intro To Java Classes

Class fundamentals, declaring class, creating objects, introducing methods: method declaration, overloading, using objects as parameters, recursion, Constructors, this keyword, garbage collection, the finalization.

Uploaded by

ankkumar835
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/ 18

Introduction to Java Programming(4CS4-06)

Unit-2: Introduction to classes: class fundamentals, declaring class, creating objects, introducing
methods: method declaration, overloading, using objects as parameters, recursion, constructors,
this keyword, garbage collection, the finalization
Introduction to class:
The class is the core of Java & it forms the basis for object-oriented programming in Java.
A class is a template for an object and an object is an instance of a class.
Every class in java forms a new data type. This new type can be used to create objects of that type.
Once class got created, we can generate as many objects as we want.
Every class defines the properties and behavior of an object.

Properties of Java Classes


• A class does not take any byte of memory.
• A class is just like a real-world entity, but it is not a real-world entity. It's a blueprint
where we specify the functionalities.
• A class contains mainly two things: Methods and Data Members.
• A class can also be a nested class.

Class characteristics:
• Identity: It is the name given to the class
• State: Represents data values that are associated with an object
• Behavior: Represents action can be performed by an object
General form:
class class-name
{
type instance_variable1;
type instance_variable2;
type instance_variableN;
type methodname1(parameter_list)
{
//body of method
}
type methodname2(parameter_list)
{
//body of method
}
type methodnameN(parameter_list)
{
//body of method
}
}

The class-name must begin with capital alphabet.


The data or variables, defined within a class are called instance variables.
The code is contained within methods. The method determine how a class data can be used.
*Java classes have a main( ) method only if that class is the starting point for the program.

e.g.
class Student
{
int rollno;
String name;
double marks;
}

Instance Variable in Java:


A variable created inside the class but outside the method is known as an instance variable. An
instance variable does not get memory at compile time; it gets memory at runtime when an object
or instance is created.
Each class instance has its own copy of instance variables, which means that changes made to
instance variables of one object do not affect the values of instance variables in other objects of
the same class.

Method in Java:
In Java method is a block of code inside a class that's intended to carry out a certain function. To
provide a mechanism to interact with the state of an object and to encapsulate behavior within
objects, methods are required.

new keyword in Java:


The new keyword is used to allocate memory at runtime. All objects get memory in the Heap
memory area.
In Java, an instance of a class-also referred to as an object-is created using the new keyword. The
new keyword dynamically allocates memory for an object of that class and returns a reference to
it when it is followed by the class name and brackets with optional arguments.

Object:
An object is an instance of a class or it is an entity that has state and behavior is known as an
object.
e.g. pen, chair, table
Pen is an object. Its name is Reynold, color is white, known as its state. It is used to write, so
writing is its behavior.
Or
An object is a variable of the type class, it is a basic component of an object-oriented programming
system. A class has the methods and data members (attributes), these methods and data members
are accessed through an object. Thus, an object is an instance of a class.
Creating an object: An object is an instance of a class. When an object of a class is created, the
class is said to be instantiated. We can create any number of objects for a class.
Syntax :
Class_name object = new Class_name([parameters]);
* parameters are optional and can be used while you're using constructors in the class.
The new operator dynamically allocates (allocates at run time) memory for an object and return a
reference to it. This reference is the address in the memory of the object allocated by new. In
Java all class objects must be dynamically allocated.

e.g.
Test ob = new Test(); // Test is class and ob is object

//program in Java for class creation of class and object


class Student
{
int id;
String name;
public static void main(String r[])
{
Student os=new Student(); //creating object
os.id=246;
os.name=”Xyz”;
System.out.println(“Student ID:”+os.id);
System.out.println(“Student Name:”+os.name);
}
}

*we can have multiple classes in single Java file. Save the program with the class name which
has main() method (i.e. Student.java).

//program in Java for multiple classes in single Java file


class Student
{
int id;
String name;
}
Class Exam
{
public static void main(String r[])
{
Student os=new Student(); //creating object
os.id=246;
os.name=”Xyz”;
System.out.println(“Student ID:”+os.id);
System.out.println(“Student Name:”+os.name);
}
}

Now, compile Exam.java source file and then run Exam.class to see the
result as follows −

C:\> javac Exam.java


C:\> java Exam
Output:
Student ID: 246
Student name: Xyz

Introducing methods in Java:


A method is a block of code or collection of statements to perform a specific task. It provides the
reusability of code. We write a method once and use it many times.
General form:
type name(parameter list)
{
//body of the method
}
type- type of value returned by the method
name – name of method

Adding method to a class


//program to check whether a given is even or odd
import java.util.*;
public class Num
{
public static void main (String args[])
{
//creating Scanner class object
Scanner ob=new Scanner(System.in);
System.out.print("Enter the number: ");
//reading value from user
int n=ob.nextInt();
//method calling
func(n);
}
//user defined method
public static void func(int n)
{
//method body
if(n%2==0)
System.out.println(n+" is even");
else
System.out.println(n+" is odd");
}
}

Output :
Enter the number: 12
12 is even

Constructor in Java:
A constructor is member function of a class with same name as the class name but no return type.
A constructor initializes an object immediately upon creation. It is called automatically after the
object is created, before the new operator completes. Constructors usually make use to initialize
all the data members of the class.
Every time an object is created, 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.
Syntax:
class-name()
{
//statements
}

Rules for Creating Java Constructor:


• Constructor name must be the same as its class name.
• A Constructor must have no explicit return type.
• A Java constructor cannot be abstract, static, final, and synchronized.
Java Constructor Java method

A constructor is used to initialize the state of A method is used to expose the behavior of
an object. an 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


The method is not provided by the compiler
constructor if we do not have any
in any case.
constructor in a class.

The constructor name must be same as the The method name may or may not be same
class name. as the class name.

Types of Java Constructors

Default constructor: These constructors do not accept any parameters. It is used to provide
default values to the objects 0, NULL etc. depending on the type.

Parameterized constructor: These constructors accept a specific number of parameters.

Syntax:
class-name(argument list)
{
//statements
}
//program in Java for default constructor
Class Student
{
int id;
String name;
public static void main(String r[])
{
Student ob=new Student();
ob.disp();
}
void disp()
{
System.out.println(“ID::”+ob.id);
System.out.println(“\nName:”+ob.name);
}
}

Output:
ID: 0
Name: null

No-argument (Parameterless) constructor:


We include explicit constructor in a class but it does not have any parameter.
e.g.
class Student
{
int id;
String name;
Student() //no-argument constructor
{
id=20;
name=”XYZ”;
}
public static void main(String r[])
{
Student ob=new Student();
ob.disp();
}
void disp()
{
System.out.println(“ID::”+ob.id);
System.out.println(“\nName:”+ob.name);
}
}

Output:
ID: 20
Name: XYZ

Parameterized constructor: These constructors accept a specific number of parameters. These


are used to provide different values to distinct objects.
e.g.
class Student
{
int id;
String name;
Student(int i,String n ) //no-argument constructor
{
id=i;
name=n;
}
void disp()
{
System.out.println(“ID::”+ob.id);
System.out.println(“\nName:”+ob.name);
}
}
Class Student1
{
public static void main(String r[])
{
Student ob1=new Student();
Student ob2=new Student(20,”Abc”);
Student ob3=new Student(21,”Xyz”);
ob1.disp();
ob2.disp();
ob3.disp();

}
}

Output:
ID: 0
Name: null
ID: 20
Name: Abc
ID: 21
Name: Xyz
Method Overloading:
In a class two or more methods that share the same name as long as their parameters are different.
When this is the case, the methods are said to be overloaded and the process is referred as method
overloading.
Method overloading in Java means two or more methods in a class with same name and different
parameters. It can be different with a different number of arguments or different type of arguments.

• Number of parameters: add(int a, int b) add(int a, int b, int c)


• Type of parameters: add(int a, int b) add(float a, float b)
• Order of parameters: calc(int a, float b) calc(float b, int a)

Method overloading is one of the ways that Java supports polymorphism.


Method overloading is resolved at compile time, making it an example of compile-time polymorphism.
The return type alone cannot differentiate overloaded methods.
When an overloaded method is invoked, Java uses the type/number pf arguments, to determine which
version of the overloaded method to actually call.

1) Method Overloading: differ in no. of arguments


// Class Calc contains overloaded methods to add integers
class Calc
{
int a,b;
Calc() //constructor
{
a=b=0;
}

int add(int i) // Method to add two integers


{
a=b=i;
return (a + b);
}

int add(int i, int j) // Method to add two integers


{
a=i;
b=j;
return a + b;
}
}

class Test
{
public static void main(String[] a)
{
Calc ob=new Calc();
// Calling the add method with one argument
System.out.println(ob.add(10)); // Output: 20
// Calling the add method with two arguments
System.out.println(ob.add(15, 16); // Output: 31
}
}
Output:
20
31

2) Method Overloading: changing data type of arguments:


// Class Calc contains overloaded methods to add numbers
class Calc
{
// Method to add two integers
int add(int a, int b)
{
return a + b;
}
// Method to add two floating numbers
double add(double a, double b)
{
return a + b;
}
}
class Test
{
public static void main(String[] r)
{
Calc ob=new Calc();
// Calling the add method with two integers
System.out.println(ob.add(10, 20); // Output: 30
// Calling the add method with two doubles
System.out.println(ob.add(10.3, 12.5)); // Output: 22.8
}
}

*Method overloading in Java is based on the method signature, which includes the method
name and parameter list. The return type alone is not sufficient to distinguish between
overloaded methods because Java does not consider the return type when resolving method
calls. If two methods have the same name and parameter list but different return types, the
compiler cannot determine which method to call based solely on the return type.
Constructor Overloading:
In Java we can overload constructors like methods. 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.
Constructor overloading is used to initialize an object in different ways.
Constructor Overloading helps in creating multiple constructors within a class, each accepting
different parameters. This can be useful in many ways such as,
1. It provides flexibility in object creation.
2. It enables you to initialize objects in different ways depending on the information
available or needed at the time of creation.
3. It also helps in making the code more simple.
e.g.
class Student
{
String name;
int id;

// parameterless constructor
Student()
{
System.out.println("Parameterless Constructor ");
name = "Abc";
id = 20;
}

// Constructor with parameters


Student(int i,String n)
{
System.out.println("Parameterized Constructor");
name = n;
id = i;
}

void disp()
{
System.out.println("Name: " + name + ", ID: " + id);
}
}

class Test
{
public static void main(String[] r)
{
Student ob1 = new Student(); // Call parameterless constructor
Student ob2 = new Student(10,"Xyz"); // Calls constructor with name parameter
ob1.disp();
ob2.disp();
}
}

Using objects as parameters:


Object as an argument is use to establish communication between two or more objects of same
class as well as different class, i.e, we can easily process data of two same or different objects
within function.
We can pass object like any other variable to a method in Java. When a primitive type is passed
to a method, it is done by use of call-by-value.
Objects are passed by use of call-by-reference. It means when we pass primitive data types to method
it will pass only values to function parameters so any change made in parameter will not affect the value of
actual parameters.
Whereas Objects in Java are reference variables, so for objects a value which is the reference to the object
is passed. Hence the whole object is not passed but its referenced gets passed. All modification to the object
in the method would modify the object.
e.g.
class Add
{
int a,b;
Add(int i, int j) // parametrized constructor
{
a = i;
b = j;
}
void sum(Add ob1)
{
int s = ob1.a + ob1.b;
System.out.println("Sum of a and b :" + s);
}
}

class Test
{
public static void main(String arg[]) {
Add ob = new Add(10, 18);
ob.sum(ob); //passing object
}
}

Output
Sum of a and b :28
Passing Object as Parameter in Constructor
class Add
{
int a, b;

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

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

void sum()
{
int s = a + b;
System.out.println("Sum of a and b :" + s);
}
}

class Test
{
public static void main(String r[])
{
Add ob = new Add(10, 5);
Add ob2 = new Add(ob);
Ob2.sum();
}
}

Output
Sum of a and b :15

‘this’ keyword in Java:


In Java, this is a reference variable that refers to the current object. It is primarily used to
differentiate between local variables and instance variables in an object. It is used within a method
or a constructor to access members of the current object such as instance variables, methods, and
constructors.
Usage of this keyword:
• this can be used to refer current class instance variable.
• this can be used to invoke current class method (implicitly)
• this() can be used to invoke current class constructor.

1. To refer current class instance variable (Instance variable hiding):


In Java in a class it is legal to declare two variables with the same name. We have local variables,
including formal parameters to methods, which overlaps with the name of class instance variables.
When a local variable has the same name as an instance variable, the local variable hides the
instance variable.
The this keyword can be used to refer current class instance variable. If there is ambiguity between
the instance variables and parameters, this keyword resolves the problem of ambiguity.
e.g.
class Student
{
int rollno;
String name;
Student(int rollno,String name)
{
this.rollno=rollno;
this.name=name;
}
void disp()
{
System.out.println(rollno+" "+name);
}
}
class Test
{
public static void main(String args[])
{
Student ob1=new Student(111,"Rohit");
Student ob2=new Student(112,"Sumit");
ob1.disp();
ob2.disp();
}
}

*The formal arguments and instance variables are same. So the local variable hides the instance
variable. So we using this keyword to distinguish local variable and instance variable.

2. To invoke current class method:


We invoke the method of the current class by using this keyword. If we don't use the this
keyword, compiler automatically adds this keyword while invoking the method.
class Abc
{
void disp()
{
System.out.println("Disp method");
}
void disp1()
{
System.out.println("Disp1 method");
this.disp();
}
}
class Test
{
public static void main(String r[])
{
Abc ob=new Abc();
ob.disp1();
}
}

3. To invoke current class constructor


this() constructor call can be used to invoke the current class constructor. It is used to reuse the
constructor or it is used for constructor chaining.

//Calling default constructor from parameterized constructor:


class Aba
{
Abc()
{
System.out.println("Parameterless constructor");
}
Abc(int x)
{
this(); //calling parameterless constructor
System.out.println(x);
}
}
class Test
{
public static void main(String r[])
{
Abc ob=new Abc(10);
}
}
Garbage collection in Java:
Garbage collection in Java is the process by which Java programs perform automatic memory
management. Java programs compile to bytecode that can be run on a Java Virtual Machine, or
JVM. When Java programs run on the JVM, objects are created on the heap, which is a portion of
memory dedicated to the program. Eventually, some objects will no longer be needed. The garbage
collector finds these unused objects and deletes them to free up memory or to reclaim the memory.

In Java dynamic memory allocation of objects is achieved using the new operator. When there are
no references to an object, it is assumed to be no longer needed and the memory occupied by the
object can be reclaimed. There is on explicit need to destroy an object as Java handles de-allocation
automatically.
*In C++ dynamically allocated objects must be manually released by use of delete operator.

Java garbage collection is an automatic process. Automatic garbage collection is the process of
looking at heap memory, identifying which objects are in use and which are not, and deleting the
unused objects.

Advantage of Garbage Collection


• It makes java memory efficient because garbage collector removes the unreferenced
objects from heap memory.
• It is automatically done by the garbage collector (a part of JVM) so we don't need to
make extra efforts.

How can an object be unreferenced?


• By nulling the reference
• By assigning a reference to another

1) By nulling a reference:
Emp ob=new Emp();
ob=null;

2) By assigning a reference to another:


Emp ob1=new Emp();
Emp ob2=new Emp();
ob1=ob2;//now the first object referred by ob1 is available for garbage collection

The finalize() method:


The finalize() method in Java is used to release all the resources used by the object before it is
destroyed by the collector. Once the clean-up activity (closing all the resources being used by an
object before it is destroyed) is done by the finalize() method, garbage collector immediately
destroys the object.
A constructor perform initialization for an object, whereas the finalize() method perform
finalization.
When object hold other kind of resources such as opening files, closing files, network connection
etc. garbage collector does not free these resources. In this case we need finalize method for an
object that perform these task such as closing files, terminating network connection etc.
The finalize() method is invoked each time before the object is garbage collected. This method
can be used to perform cleanup processing. This method is defined in Object class as:
protected void finalize()
{
//finalization code
}

gc() method:
The gc() method is used to invoke the garbage collector to perform cleanup processing. The gc()
is found in System and Runtime classes.
public static void gc()
{
}

// Example of garbage collection in java


public class Test
{
public void finalize()
{
System.out.println("object is garbage collected");
}
public static void main(String r[])
{
Test s1=new Test();
Test s2=new Test();
s1=null;
s2=null;
System.gc();
}
}
Output:
object is garbage collected
object is garbage collected
Recursion:
It is a process in which a method call itself repeatedly. A method that call itself is called
recursive method.
Syntax:
return-type func()
{
-
-
func(); //calling itself
}

//Java program to find factorial of a given number using recursion


class Exam
{
int fact(int n)
{
if (n == 1)
return 1;
else
return(n * fact(n-1));
}

public static void main(String[] r)


{
System.out.println("Factorial of 5 is: "+fact(5));
}
}

You might also like