Classes and Objects: Unit 2
Classes and Objects: Unit 2
Classes and Objects: Unit 2
CST364
Classes
A class can be defined as a template/blueprint that
describes the behavior/state that the object of its type
support.
A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
Circle
centre
radius
circumference()
area()
Classes
A class can be defined as a template/blueprint that
describes the behavior/state that the object of its type
support.
A class is a collection of fields (data) and methods
(procedure or function) that operate on that data.
Circle
centre
radius
circumference()
area()
4
Classes
A class is a collection of fields (data) and methods (procedure or
function) that operate on that data.
The basic syntax for a class definition:
public class ClassName {
// fields fieldType fieldName;
// methods public returnType
methodName()
{ statements; }
}
Bare bone class – no fields, no methods
public class Circle {
// my circle class
}
5
Instance variable in Java
A variable which is created inside the class but outside
the method, is known as instance variable. Instance
variable doesn't get memory at compile time. It gets
memory at run time when object(instance) is created.
That is why, it is known as instance variable.
6
Adding Fields: Class Circle with
fields
Add fields
public class Circle {
public double x, y; // centre coordinate
public double r; // radius of the circle
float area (double r);
}
7
Adding Methods
A class with only data fields has no life. Objects
created by such a class cannot respond to any
messages.
Methods are declared inside the body of the class but
immediately after the declaration of data fields.
The general form of a method declaration is:
type MethodName
(parameter-list)
{
Method-body;
8 }
Adding Methods to Class Circle
10
Creating objects of a class
aBankAcc = new BankAccount() ;
bBankAcc = new BankAccount() ;
bBankAcc = aBankAcc;
P Q P Q
11
Classes using function
class TestStudent4 class Student4{
{ int rollno;
public static void main(String args[]) String name;
{ void insertRecord(int r, String n)
Student4 s1=new Student4(); {
Student4 s2=new Student4(); rollno=r;
s1.insertRecord(111,"Karan"); name=n;
s2.insertRecord(222,"Aryan"); }
s1.displayInformation(); void displayInformation()
s2.displayInformation(); {
} System.out.println(rollno+" "+name);}
} }
12
Create a Class and an Object
class Person {
}
public class Application {
public static void main(String[] args) {
System.out.println("Hello World!");
Person person = new Person();
}
}
13
Exercise1 : getMethod() & setMethod()
15
Solution Contd…
16
Exercise 2: Write Text
-Based Application using Object-Oriented Approach to display your
name.
17
Exercise 3: Client code method call syntax
18
Accessing Object/Circle Data
Similar to C syntax for accessing data defined in a
structure.
ObjectName.VariableName
ObjectName.MethodName(parameter-list)
double area;
aCircle.r = 1.0;
area = aCircle.area();
20
Using the Class
class Sdate {
int month, day, year;
void setDate(int m,int d,int y)
{
month=m;
day=d;
year=y;
System.out.println(month+” “+ day+” “+year);
}
public static void main(String args[])
{
Sdate S1,S2;
S1=new Sdate();
S2=new Sdate();
S1.setDate(11,27,1967);
S2.setDate(4,3,1969);
} }
Defining Objects
Statement Effect
S1 = new Sdate()
S1 Month
Day
Year
S1 object
Object Reference
Points to Physical
New operator create location of
S1 data
class Sdate{
S1 ………….
……….
Sdate S1 = new Sdate();
S2 Sdate S2 = S1;
………..
}
Calling methods
Syntax: Class.object.method()
Passing Parameters
Call by value
Call by reference
Call by Value
/* Example of Call by Value */
class Test {
void change(int m,int n)
{
m = m * 2;
n = n + 3;
System.out.println(“The value of m = “+ m + “ and
the value of n = “+n);
}
public static void main(String args[])
{
Test S1;
S1=new Test();
int a=10, b=12;
System.out.println(“Before : The value of a = “ +a +“
and the value of b = “ + b);
S1.change(a,b);
System.out.println(“After : The value of a = “ +a + “
and the value of b = “ + b);
} }
Call by Reference
class Test {
int m,n;
Test() {
m=10;
n=20;
}
void change(Test T1) {
T1.m = T1.m * 2;
T1.n = T1.n + 3;
}
public static void main(String args[]) {
Test S1 = new Test();
Test S2 = S1; //assigning reference of object S1 to S2
System.out.println("Before : The value of m = "+S1.m + "and the
value of n = " + S1.n);
S1.change(S2);
System.out.println("After : The value of m = "+ S1.m + " and the
value of n = " + S1.n);
}
}
Returning object from a method
30
Taking input from user
import java.io.*;
32
Constructor and types
Constructor
Constructor in java is a special type of method that is
used to initialize the object.
Java constructor is invoked at the time of object creation.
It constructs the values i.e. provides data for the object
that is why it is known as constructor.
Rules for creating java constructor
There are basically two rules defined for the constructor.
Constructor name must be same as its class name
Constructor must have no explicit return type
Constructor (cont.)
A constructor does look and feel a lot like a method but
it is different from a method in two ways:
A constructor always has a same name as the class whose
instance members they initialize.
A constructor does not have a return type, not even void.
It is because the constructor is automatically called by the
compiler whenever an object of the class is created.
Types of java constructors
There are three types of constructors:
Default constructor (no-arg constructor)
Parameterized constructor
Copy Constructor
Example of default constructor
class Bike1{
Bike1()
{
System.out.println("Bike is created");
}
public static void main(String args[]){
Bike1 b=new Bike1();
}
}
Example of parameterized constructor
class Studentdetails{
int id;
String name;
Studentdetails(int i,String n){
id = i;
name = n;
}
void display()
{
System.out.println(id+" "+name);}
public static void main(String args[]){
Studentdetails s1 = new Studentdetails(100,”Amol");
Studentdetails s2 = new Studentdetails(222,"Archana");
s1.display();
s2.display();
}
}
Constructor example
class Circle{
double r;
public static void main(String[] args){
Circle c2 = new Circle(); // OK, default constructor
Circle c = new Circle(2.0); //error!!
}
}
Constructor Overloading in Java
class Circle{
double r;
public Circle(){
r = 1.0; //default radius value;
}
public Circle (double r) {
this.r = r; //same name!
}
public static void main(String[] args){
Circle c = new Circle(2.0); //OK
Circle c2 = new Circle(); // OK now!
}
}
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.
So, we perform method overloading to figure out the program quickly.
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
Method Overloading: changing no. of
arguments
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));
}}
Method Overloading: changing data type
of 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));
}}
Array of Objects
An array of objects in Java is just a list of reference variables that contain normally addresses
to the individual objects.
The array of Objects the name itself suggests that it stores an array of objects. Unlike the
traditional array stores values like String, integer, Boolean, etc.
An Array of Objects stores objects that mean objects are stored as elements of an array.
Creating an Array Of Objects
We use the Class_Name followed by a square bracket [] then object reference name to
create an Array of Objects.
Class_Name[ ] objectArrayReference;
OR
Class_Name objectArrayReference[ ];
For example, if you have a class Student then we can create an array of Student objects as
given below:
Student[ ] studentObjects;
Or
Student studentObjects[];
Array of Objects
Instantiate the array of objects –
For example, if you have a class Student, and we want to declare and instantiate an
array of Student objects with two objects/object references then it will be written
as:
Student[ ] studentObjects = new Student[2];
And once an array of objects is instantiated like this, then the individual elements of
the array of objects needs to be created using the new keyword.
The below figure shows the structure of an Array of Objects :
Conti..
class Main{ //Employee class constructor
public static void main(String args[]){ Employee(inteid, String n){
//create array of employee object empId = eid;
Employee[] obj = new Employee[2] ;
name = n;
//create & initialize actual employee objects }
using constructor public void showData(){
obj[0] = new Employee(100,"ABC"); System.out.print("EmpId = "+empId + " " +
obj[1] = new Employee(200,"XYZ"); " Employee Name = "+name);
System.out.println();
//display the employee object data }
System.out.println("Employee Object 1:"); }
obj[0].showData();
System.out.println("Employee Object 2:");
obj[1].showData();
}
}
//Employee class with empId and name as
attributes
class Employee{
int empId;
String name;
Example
class Student Student students[]=new Student[3];
{ students[0]=s1;
int rollno; students[1]=s2;
String name; students[2]=s3;
int marks; for(int i=0;i<students.length;i++)
} {
public class Demo System.out.println(students[i].name+":"+st
{ udents[i].marks); }
public static void main(String[] args)
{ Student s1=new Student(); }}
s1.rollno=1;
s1.name="Navin";
s1.marks=88;
Student s2=new Student();
s2.rollno=2;
s2.name="Harsh";
s2.marks=67;
Student s3=new Student();
s3.rollno=3;
s3.name="Kiran";
s3.marks=97;
System.out.println(s1.name + ":"+ s1.marks);