UNIT-2 Introduction to Classes, Objects and Methods
Department of Computer Science and Engineering
Topics:
1. Class Fundamentals, Objects creation, Reference Variables and
Assignment
2. Methods, Returning a Value, Using Parameters
3. Constructors, Parameterized Constructors, new Operator, this Keyword,
finalize() method
4. Wrapper Classes, Parsing, Auto boxing and Unboxing
5. I/O: Command-Line Arguments, Scanner and Buffered Reader Classes,
Department of CSE
Syntax of Class
Class Fundamentals class ClassName {
type instance-variable1;
type instance-variable2;
The entire Java language is built in with classes, because it // ...
defines the shape and nature of the Object. type instance-variableN;
A class is a user defined data type. Once the class is defined,
the ‘new’ type can be used to create Object of that type. type methodName1(parameter-list)
{
A class is a template for an object, and an object is an // body of method
instance of a class.
}
When you define a class, you can declare its exact form and type methodName2(parameter-list)
nature. {
A class is declared by the use of the “class” keyword. // body of method
}
The data or the variable defined within the class are called
“Instance Variables”. // ...
type methodNameN(parameter-list)
The code is contained within methods. {
the methods and variables defined within a class are called // body of method
members of the class. }
Department of CSE }
class Box {
double width;
A Simple Class double height;
double depth;
// create a class named Box }
class Box {
// create a class named Box // This class declares an object of type Box.
double width; public class BoxDemo {
class Box {
double height;
double width;
public static void main(String args[ ]) {
Box mybox = new Box();
double depth;
double height; double vol;
} double depth; // assign values to mybox's instance variables
} mybox.width = 10;
mybox.height = 20;
Box mybox = new Box(); mybox.depth = 15;
// compute volume of box
vol = mybox.width * mybox.height * mybox.depth;
mybox.width = 100; System.out.println("Volume is " + vol);
}
}
Department of CSE
Object Creation
Box mybox = new Box();
Box mybox; // declare reference to object
mybox = new Box(); // allocate a Box object
Department of CSE
Assigning Object Reference Variables
Box mybox = new Box();
Box mybox1 = mybox;
Department of CSE
Methods
Classes usually consist of two things: instance variables and methods.
type method_name(parameter-list) {
// body of method
Department of CSE
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
// This program includes a method inside the box
// assign values to mybox1's instance variables
class.
mybox1.width = 10;
class Box {
mybox1.height = 20;
double width;
mybox1.depth = 15;
double height;
/* assign different values to mybox2's
double depth;
instance variables */
// display volume of a box
mybox2.width = 3;
void volume() {
mybox2.height = 6;
System.out.print("Volume is ");
mybox2.depth = 9;
System.out.println(width * height * depth);
// display volume of first box
}
mybox1.volume();
}
// display volume of second box
mybox2.volume();
}
Department of CSE }
class BoxDemo3 {
Returning a Value public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
// This program includes a method inside the // assign values to mybox1's instance variables
box class. mybox1.width = 10;
class Box { mybox1.height = 20;
double width; mybox1.depth = 15;
/* assign different values to mybox2's
double height;
instance variables */
double depth; mybox2.width = 3;
// display volume of a box mybox2.height = 6;
double volume() { mybox2.depth = 9;
return width * height * depth; // get volume of first box
vol = mybox1.volume();
}
System.out.println("Volume is " + vol);
} // get volume of second box
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
Department of CSE
}
Method without parameters
Method with
parameters
int square()
{ int square(int i)
return 10 * 10; {
} return i * i;
}
int x;
x = square(5); // x equals 25
x = square(9); // x equals 81
Department of CSE
// This program uses a parameterized method. class BoxDemo5 {
class Box { public static void main(String args[]) {
double width; Box mybox1 = new Box();
double height; Box mybox2 = new Box();
double depth; double vol;
// compute and return volume // initialize each box
double volume() { mybox1.setDim(10, 20, 15);
return width * height * depth; mybox2.setDim(3, 6, 9);
} // get volume of first box
// sets dimensions of box vol = mybox1.volume();
void setDim(double w, double h, double d) { System.out.println("Volume is " + vol);
width = w; // get volume of second box
height = h; vol = mybox2.volume();
depth = d; System.out.println("Volume is " + vol);
} }
} }
Department of CSE
Constructors
• A constructor is a special method whose task is to initialize the
objects of its class.
• It is a special method because its name is same as the class name.
• The constructor is syntactically similar to a method.
• Once the constructor is defined it automatically called after the object
is created before the new operator completes.
• These constructors have no return type, even void also.
Department of CSE
Types of Constructors
Two types of constructors:
Default Constructor
Parameterized Constructor
• A constructor that accepts no parameters is called the “Default Constructor”.
• The Default constructor automatically initializes all instance variable to zero(0).
• If you don’t implement any constructor in your class, the Java compiler inserts default
constructor into your code on your behalf.
• You will not see the default constructor in your source code(the .java file) as it is inserted during
compilation and present in the bytecode (.class file).
Department of CSE
Types of Constructors
Two types of constructors:
Default Constructor and
Parameterized Constructor
• The constructors are the constructors having a specific number of arguments to be passed.
• The purpose of a parameterized constructor is to assign user-wanted specific values to the
instance variables of different objects.
• A parameterized constructor is written explicitly by a programmer.
Department of CSE
Default Constructor
class Box {
double width; class BoxDemo6 {
double height; public static void main(String args[]) {
double depth; Box mybox1 = new Box();
// This is the constructor for Box. Box mybox2 = new Box();
Box() { double vol;
System.out.println("Constructing Box"); // get volume of first box
width = 10; vol = mybox1.volume();
height = 10; System.out.println("Volume is " + vol);
depth = 10; // get volume of second box
} vol = mybox2.volume();
// compute and return volume System.out.println("Volume is " + vol);
double volume() { }
return width * height * depth; }
}
}
Department of CSE
Parameterized Constructors
class Box {
double width; class BoxDemo7 {
double height; public static void main(String args[]) {
double depth; Box mybox1 = new Box(10, 20, 15);
// This is the constructor for Box. Box mybox2 = new Box(3, 6, 9);
Box(double w, double h, double d) { double vol;
width = w; // get volume of first box
height = h; vol = mybox1.volume();
depth = d; System.out.println("Volume is " + vol);
} // get volume of second box
// compute and return volume vol = mybox2.volume();
double volume() { System.out.println("Volume is " + vol);
return width * height * depth; }
} }
}
Department of CSE
The this Keyword
this can be used inside any method to refer to the current object.
1. Refers to the current class instance.
2. Differentiates between instance variables and method parameters.
3. Invokes current class methods (this.methodName()).
4. Calls current class constructors (this()).
5. Passes the current object as a method/constructor argument.
6. Returns the current class instance.
7. Refers to an outer class instance in nested classes.
The this keyword is an essential concept in Java for handling ambiguity and
managing class objects efficiently.
Department of CSE
The this Keyword (Refers to the current class instance.)
class Sample {
int n1; class Sample {
int n2; int n1;
Sample(int n1, int n2) { int n2;
n1=n1; Ambiguity
Sample(int n1, int n2) {
n2=n2; Situation this.n1 = n1
}
this.n2 = n2
void display() {
System.out.println(n1+” ”+n2); }
} void display() {
} System.out.println(n1+” ”+n2);
}
}
Department of CSE
The this Keyword (Differentiates between instance variables
and method parameters.)
Refer to slide 11 example
Refer to slide 16 example
Department of CSE
The this Keyword
(Invokes current class methods (this.methodName())
class Example {
void method1() {
System.out.println("Method1 called");
}
void method2() { public class Main {
System.out.println("Method2 called"); public static void main(String[] args)
this.method1(); // Calls method1 from {
the same class Example obj = new Example();
} obj.method2();
} }
}
Department of CSE
The this Keyword
(Calls current class constructors (this()).
this() can be used to call another constructor in the same class.
It must be the first statement in the constructor.
class Example {
Example() {
this(10); // Calls the parameterized constructor
System.out.println("Default constructor"); public class Main {
} public static void main(String[] args)
Example(int num) { {
System.out.println("Parameterized constructor: " + Example obj = new Example();
num); }
} }
}
Department of CSE
The this Keyword
(Passes the current object as a method/constructor argument)
You can pass the current object (this) as an argument to a method,
enabling the method to operate on that instance.
class Example {
void display(Example obj) { public class Main {
// Method accepts an Example object public static void main(String[] args)
System.out.println("Method called with current {
object reference"); Example obj = new Example();
} obj.callDisplay();
// Output: Method called with current
void callDisplay() { object reference
display(this); // Passing the current object }
} }
}
Department of CSE
The this Keyword
(Returns the current class instance)
In Java, the this keyword can be used to return the current class instance from a
method.
This is particularly useful for method chaining, where multiple methods are called on
the same object in a single statement.
Department of CSE
The this Keyword
(Returns the current class instance.)
class Example {
int num;
// Method that sets the value of num
Example setNum(int num) { public class Main {
this.num = num; public static void main(String[] args)
// Assigning value to the instance variable {
return this; // Returning the current instance Example obj = new Example();
} obj.setNum(10).display();
/* Method chaining: Calling display()
// Method to display the value of num on the same object*/
void display() { }
System.out.println("Value of num: " + num); }
}}
Department of CSE
The this Keyword
(Returns the current class instance.)
1.setNum(int num) Method:
•Assigns the value of the parameter num to the instance variable
using this.num = num.
•Returns the current instance (this) to allow further method calls on
the same object.
2.Chaining Method Calls:
•After setNum(10) is called, the returned instance of the class
allows you to immediately call display().
Department of CSE
The this Keyword
(Refers to an outer class instance in nested classes)
When an inner class (non-static nested class) is created, it has a
reference to the outer class instance.
You can explicitly use OuterClassName.this to refer to the outer
class's instance from within the inner class.
Department of CSE
The this Keyword
(Refers to an outer class instance in nested classes)
class Outer {
int x = 10;
class Inner { public class Main {
int x = 20; public static void main(String[] args)
{
void display() { Outer outer = new Outer();
System.out.println("Inner class x: " + x); Outer.Inner inner = outer.new
// Refers to inner class x Inner(); // Create an instance of the
System.out.println("Outer class x: " + inner class
Outer.this.x); inner.display();
// Refers to outer class x }
} }
}
}Department of CSE
Garbage Collection
when no references to an object exist, that object is assumed to be no
longer needed, and the memory occupied by the object can be
reclaimed.
finalize( ) method
Sometimes an object will need to perform some action when it is
destroyed.
protected void finalize( )
{
// finalization code here
}
Department of CSE
Wrapper Classes
The wrapper classes in Java are used to convert primitive types into corresponding objects and
objects into primitive types.
Primitive types Wrapper classes
boolean Boolean
char Character
byte Byte
short Short
int Integer
long Long
float Float
double Double
Department of CSE
Autoboxing and Unboxing
Autoboxing: Primitive Type to Wrapper Object
Two ways of autoboxing: using constructor and using valueOf() method.
Example:
Integer obj = new Integer(10);
Integer obj = Integer.valueOf(10);
Unboxing: Wrapper Objects to Primitive Types
It can be done using corresponding value() method. Example: obj.intValue(),
obj.doubleValue(), etc.
Example:
int i = obj.intValue();
Department of CSE
Parsing
The parse() method receives some string as input, "extracts" the necessary information from it.
Example:
Integer.parseInt() to convert string into int
Double.parseDouble() to convert string into double
Department of CSE
Java Command Line Arguments
The java command-line argument is an argument i.e. passed at the time of running the java program.
class CmdDemo{
public static void main(String args[]){
int count = args.length;
for(int i=0;i<count;i++)
System.out.println(args[i]);
}
}
Department of CSE
Java Scanner Class
The Scanner class of the java.util package is used to read input data from different sources like input
streams, users, files, etc.
Scanner sc = new Scanner(System.in);
int i = sc.nextInt();
Some important methods
nextInt()
nextDouble()
nextFloat()
nextLine()
toString()
next()
Department of CSE
BufferedReader class
Reads input from either System.in or file
InputStreamReader class is used to read input from System.in
FileReader class is used to read input from file
After reading from any of these classes, it creates a buffer of character set.
BufferedReader class is used to read from the buffered character set.
Department of CSE
Reading from System.in
InputStreamReader ir = new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(ir);
Reading from File
FileReader fr = new FileReader(System.in)
BufferedReader br = new BufferedReader(fr);
Department of CSE
Methods in BufferedReader
read()
readLine()
InputStreamReader ir = new InputStreamReader(System.in)
BufferedReader br = new BufferedReader(ir);
String str = br.readLine();
Department of CSE
import java.io.*;
class B
{
public static void main(String args[]) throws IOException
{
InputStreamReader ir = new InputStreamReader(System.in);
BufferedReader br = new BufferedReader(ir);
String str = br.readLine();
System.out.println("String is "+str);
}
}
Department of CSE
Thank You
All the Best
Department of CSE