Classes and Objects: Unit 2

Download as pdf or txt
Download as pdf or txt
You are on page 1of 52

UNIT 2

Classes and Objects

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

The fields (data) are also called the instance variable.

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

public class Circle {

public double x, y; // centre of the circle


public double r; // radius of circle

//Methods to return circumference and area


public double circumference() {
return 2*3.14*r;
}
public double area() {
return 3.14 * r * r; Method
Body
}
}
9
Creating objects of a class
Objects are created dynamically using the new keyword.
aBankAcc and bBankAcc refer to BankAccount objects

aBankAcc = new BankAccount() ; bBankAcc = new BankAccount() ;

10
Creating objects of a class
aBankAcc = new BankAccount() ;
bBankAcc = new BankAccount() ;

bBankAcc = aBankAcc;

Before Assignment Before Assignment


aBankAcc bBankAcc aBankAcc bBankAcc

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

Modify your main of Applications Class method like this:


1. Use getName to retrieve the name String from the Person
object (in the main method, remember!). Store it there
temporarily.
2. Add a space followed by your surname to the String you just
retrieved.
3. Use the setName method to set the name instance variable of
your person object to the full name that you've just created.
Do all this just before calling writeName().
Hint: none of this involves editing the Person class! All your
editing should take place in main.
Solution
class Person { public void setName(String name) {
private String name; this.name = name;
public Person() { }
}
public Person(String name) { public String getName() {
this.name = name; return name;
} }
public void writeName() { }
System.out.println("My name is " +
name);
}

15
Solution Contd…

public class Application {


public static void main(String[] args) {
System.out.println("Hello World!");
Person person = new Person(“Shweta");
String name = person.getName();
name = name + " Bondre";
person.setName(name);
person.writeName();
}
}

16
Exercise 2: Write  Text
-Based  Application using  Object-Oriented Approach to  display  your 
name.

public class Name {


public void display()
{ System.out.println("Mohamed Faisal"); }}

public class DisplayName {


public static void main(String[] args) {
Name myname = new Name();
myname.display();
}}

17
Exercise 3: Client code method call syntax

Suppose a method in the BankAccount class is defined as:


public double computeInterest(int rate)

If the client code has declared a BankAccount variable named


acct, which of the following would be a valid call to the above
method?

▪ double result = computeInterest(acct, 42);


▪ int result = BankAccount.computeInterest(42);
▪ double result = acct.computeInterest(42);
▪ acct.computeInterest(42.0, 15);

18
Accessing Object/Circle Data
Similar to C syntax for accessing data defined in a
structure.

ObjectName.VariableName
ObjectName.MethodName(parameter-list)

Circle aCircle = new Circle();

aCircle.x = 2.0 // initialize center and radius


aCircle.y = 2.0
aCircle.r = 1.0
19
Executing Methods in Object/Circle
Using Object Methods:

sent ‘message’ to aCircle

Circle aCircle = new Circle();

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

Sdate S1; Null

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

A method is always called to act on a specific object,


not on the class in general
Example: S1.setdate(27,1,1969)

The general syntax for accessing a member function


of a class is

Syntax: Class.object.method()
Passing Parameters

void setDate(int m,int d,int y)


Passing
{
Parameters day=d;
year=y;
month=m;
}
Formal
parameter

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

A return statement in a function is considered to


initialize a variable of the returned type
Syntax:
Test testobjectS1.func()
test func ()
{
test temp_object;
.
.
return temp_object;
}
Taking input from user
import java.util.*;

Scanner in = new Scanner(System.in);  


System.out.println("Enter a string");
String s = in.nextLine();
int a = in.nextInt();
float b = in.nextFloat();
User input program
import java.util.Scanner;  
class ScannerTest{  
 public static void main(String args[]){  
   Scanner sc=new Scanner(System.in);  
     System.out.println("Enter your rollno");  
   int rollno=sc.nextInt();  
   System.out.println("Enter your name");  
   String name=sc.next();  
   System.out.println("Enter your fee");  
   double fee=sc.nextDouble();  
   System.out.println("Rollno:"+rollno+" name:"+name+" fee:"+fee);  
   sc.close();  
 }  
}   

30
Taking input from user
import java.io.*;

BufferedReader bufferedReader = new BufferedReader(new


InputStreamReader(System.in));

String input = bufferedReader.readLine();


float n=Float.parseFloat(input);
int n1= Integer.parseInt(input);
double number = Double.parseDouble(input);
Exercise based on classes & Objects
Implement a simple calculator
WAP to display how many programming languages a students knows?
Write a program to determine the sum of the series: 1-1/2+1/3-1/4+…..+1/n. (Take
value of n from the user)
Write a program to accept number through Command line and display its factorial.
WAP for Employee record keeping
WAP to find the average and sum of the N numbers Using Command line argument.
WAP to Demonstrate Type Casting.
WAP to find the number of arguments provide at runtime.
Write a program to display a greet message according to Marks obtained by student
Write a program to Swap the values (call by value & call by reference)
Write a simple Java Program to get the input meters from keyboard and convert to
kilometers

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

Constructor overloading is a technique in Java in which a


class can have any number of constructors that differ in
parameter lists.
The compiler differentiates these constructors by taking
into account the number of parameters in the list and
their type.
Example of Constructor Overloading
void display()
class Studentdetails{ {
int id; System.out.println(id+" "+name+" "+age);}
String name;
int age; public static void main(String args[]){
Studentdetails(int i,String n){ Studentdetails s1 = new
id = i; Studentdetails(101,”meenal");
name = n; Studentdetails s2 = new
} Studentdetails(102,”mohan",25);
Studentdetails(int i,String n,int a){ s1.display();
id = i; s2.display();
name = n; }
age=a; }
}
Constructor Overloading example

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!
}
}

Multiple constructor now!!


Constructor Example

class Rectangle class ParamConstructorDemo


{ {
int length; public static void main(String args[])
int breadth; {
Rectangle(int l, int b) Rectangle firstRect=new Rectangle(5,6);
{ Rectangle secondRect=new Rectangle(7,8);
length=l; breadth=b; System.out.println("Area of first
rectangle="+firstRect.area());
}
System.out.println("Area of second
int area() rectangle="+secondRect.area());
{ }
return (length*breadth);
}
}
Copy Constructor
class JavaExample{
String web;
JavaExample(String w){
web = w;
}
JavaExample(JavaExample je){
web = je.web;
}
void disp(){
System.out.println("Website: "+web);
}

public static void main(String args[]){


JavaExample obj1 = new JavaExample("BeginnersBook");

JavaExample obj2 = new JavaExample(obj1);


obj1.disp();
obj2.disp();
}
}
Copy Constructor example
class Student6{ void display(){System.out.println(id+"
"+name);}
int id,age;
String name;
public static void main(String args[]){
Student6(int i,String n){
Student6 s1 = new
id = i; Student6(111,"Karan");
name = n; Student6 s3 = new Student6(s1);
} Student6 s2 = new
Student6(Student6 s){ Student6(222,"Karishma“,19);
id = s.id; s1.display();
name =s.name; s2.display();
} S3. display() }
Student6(int i,String n,int a){ }
id = i;
name = n;
age=a; }
Method Overloading
Method Overloading allows different methods to have the same name, but different
signatures where the signature can differ by the number of input parameters or type of
input parameters, or a mixture of both.

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

You might also like