Chapter 05 - Objects and Classes in Java
Chapter 05 - Objects and Classes in Java
Chapter 05 - Objects and Classes in Java
1
Outline
Concept of Class
Class members
General form of a Java class
Fields
Fields Declaration
Methods
Method Definition
Method invocations
Concept of Objects
Access Control: Data Hiding and Encapsulation
Constructors
Keyword this
Garbage collection
Finalize method
Method overloading
Constructor overloading
Parameter passing
Recursion
Java Example programs 2
Concept of Class
A class is essential element of Object Oriented Programming
A class is the template or prototype that defines the states
and the behaviors common to all objects of a certain kind.
It is the collection of objects of similar type
When a class is created it means new data type has been
created.
Classes are user define data types and behave like built in
types of programming language.
If you are creating class, you are doing encapsulation.
Encapsulation simply means binding object state(fields)
and behaviors (methods) together in to single unit.
Class Members
A class can have three kinds of members:
fields:
That hold the object’s state
data variables which determine the status of the class or
an object
methods:
that describe the object’s behaviors
executable code of the class built from statements. It
allows us to manipulate/change the status of an object or
access the value of the data member
nested classes and nested interfaces [optional]
General form of a Java Class
In general, a simple class declarations can include these
components, in order:
Modifiers: A class can be public or has default access
Class name: The name should begin with a capital letter
(capitalized by convention).
Superclass(if any): The name of the class’s parent (superclass),
if any, preceded by the keyword extends. A class can only
extend (subclass) one parent.
Interfaces(if any): A comma-separated list of interfaces
implemented by the class, if any, preceded by the keyword
implements. A class can implement more than one interface.
Body: The class body surrounded by braces, { }.
In the body of class we define states and behaviors which are
common to all objects of that class.
Fields
In the body of class we define states and behaviors which are
common to all objects of that class.
define the variables/fields that hold the object’s state
define the methods that describe the object’s behaviors
Field Declaration
field declarations can be preceded by different modifiers
access control modifiers
static/non static (by default)
final
Followed type name followed by the field name, and optionally
an initialization clause
primitive data type or Object reference
boolean, char, byte, short, int, long, float, double
Fields
Fields Declaration
Access control modifiers
private: private members are accessible only in the class
itself
package: package members are accessible in classes in
the same package and the class itself
protected: protected members are accessible in classes
in the same package, in subclasses of the class, and in
the class itself
public: public members are accessible anywhere the
class is accessible
Fields
Fields Declaration
Non static(instance) data members
Each object contains separate copy of these variables. This is
known as non static or instance data members.
By default (when we don’t specify static), the data member is
to be considered as instance data member.
can be accessed directly in the class itself
from outside the class, public/package non-static fields must
be accessed through an object reference.
From outside the class, private/protected data members can
be accessed through methods
Can not be accessed directly i.e. through an object reference
Fields
Fields Declaration
Static data members
only one copy of the static field exists, shared by all objects of
this class
can be accessed directly in the class itself
access from outside the class must be preceded by the class
name as follows
System.out.println(Pencil.nextID);
or via an object belonging to the class
Fields
Field Declaration
Final (optional if it is required)
once initialized, the value cannot be changed
often be used to define named constants
static final fields must be initialized when the class is
initialized
non-static final fields must be initialized when an object
of the class is constructed
Methods
Method Definition
1) method header
consists of modifiers (optional), return type,
method name, parameter list and a throws clause
(optional)
types of modifiers
access control modifiers
abstract
the method body is empty. E.g.
abstract void sampleMethod( );
Used within in abstract classes(classes cannot be instantiated)
static
represent the whole class, no a specific object
can only access static fields and other static methods of the same class
final
cannot be overridden in subclasses
2) method body
Methods
Method Invocation/Calling
invoked as operations on objects/classes using the dot ( . )
operator
reference.method(arguments)
static method:
Outside of the class: “reference” can either be the class name or an
object reference belonging to the class
Inside the class: “reference” can be ommitted
non-static method:
“reference” must be an object reference
Objects
An object is an instance of a class
It is a basic unit of Object Oriented Programming and represents
the real life entities.
Once a class is created/already exist, we can create many objects,
which interact by invoking methods. An object consists of :
State: represents the data (value) /attributes of an object. It also
reflects the properties of an object.
Behavior: represents the behavior (functionality)/operation of an
object such as deposit, withdraw, etc. it is represented by methods
of an object.
Identity: It gives a unique name to an object and enables one object to
interact with other objects.
An object can perform only those operations/behaviors/actions
which are defined within the body of the class.
New keyword is used to create an object of particular class.
The new keyword is used to allocate memory at runtime.
Lamp Class
Every object of class lamp can either be set either ONN or Off.
The lamp object can perform two operations/actions.
turnOn(set) operation will set the isOn=true and turnOff(reset)
operation will retset the isOn=False.
State(s):
isOn=true/false
Behaviors:
turnOn( )
turnOff( )
// java program to create and test Lamp class
class Lamp
{ class Main
boolean isOn; {
public static void main(String[] args)
void turnOn()
{
{ // create objects l1 and l2
// initialize variable with value true Lamp l1 = new Lamp();
isOn = true; Lamp l2 = new Lamp();
System.out.println("Light on? " + isOn); // call methods turnOn() and turnOff()
} l1.turnOn();
l2.turnOff();
void turnOff()
}
{ }
// initialize variable with value false
isOn = false;
System.out.println("Light on? " + isOn);
}
}
Ways to initialize object
There are 3 ways to initialize object in Java.
1) By reference variable
2) By method
3) By constructor
3D Box class
State(s): (Attributes)
Length, width, height
Behaviors: (Methods)
Set,volume,get,show
class Box // compute and return volume
{ double volume()
double width; {
double height; return width * height * depth;
double depth; }
// constructor used when all dimensions specified void showBox()
Box(double w, double h, double d) {
{ System.out.println("The width="+width);
width = w; System.out.println("The height="+height);
height = h; System.out.println("The depth="+depth);
depth = d; }
} void getBox()
// constructor used when no dimensions specified {
Box() Scanner kb=new Scanner(System.in);
{ System.out.println("Enter width");
width = -1; // use -1 to indicate width=kb.nextDouble();
height = -1; // an uninitialized System.out.println("Enter height");
depth = -1; // box height=kb.nextDouble();
} System.out.println("Enter depth");
// constructor used when cube is created depth=kb.nextDouble();
Box(double len) }
{ }// closing brace for class body
width = height = depth = len;
}
public class BoxDemo
{
public static void main(String []args)
{
// create boxes using the various constructors
Box mybox1 = new Box(10, 20, 15);
Box mybox2 = new Box();
Box mycube = new Box(7);
double vol;
// get volume of first box
vol = mybox1.volume();
System.out.println("Volume of mybox1 is " + vol);
// get volume of second box
vol = mybox2.volume();
System.out.println("Volume of mybox2 is " + vol);
// get volume of cube
vol = mycube.volume();
System.out.println("Volume of mycube is " + vol);
}
}
The Circle class
The Circle contains three dimension: (data members)
xCenter,yCenter //location of a circle.
Radius // radius of a circle
Count static member
This class contains : (methods)
various constructors to initialize the cirlce
cirlceArea to calculate area of a circle
circleCircum to calculate circumference of a circle
getCircle method to get dimensions of the circle from user
and showCircle method to display dimensions of the circle
Static method getCount to determine number of circle objects are created
Cirlce class
State(s): (Attributes)
xCenter,yCenter,Radius,count
Behaviors: (Methods)
Set,Area,Circum,get,show ,getcount
class Circle
{ void showCircle()
private int x; {
private int y; System.out.println();
double radius; System.out.println("x="+x);
private static double pi=3.14; System.out.println("y="+y);
private static int count=0; System.out.println("radius="+radius);
//constructors
Circle() }
{ void getCircle()
x=0; {
y=0; Scanner input=new Scanner(System.in);
radius=0.0; System.out.println();
count++;
System.out.print("Enter x=");
}
x=input.nextInt();
Circle(int x,int y,double rad)
System.out.print("Enter y=");
{
this.x=x; y=input.nextInt();
this.y=y; System.out.print("Enter radius=");
radius=rad; radius=input.nextDouble();
count++; }
} static int getCount()
double areaCircle() {
{ return count;
return (pi*radius*radius); }
} }
double circumCircle()
{
return (2*pi*radius*radius);
}
import java.util.Scanner;
public class DemoCircle
{
public static void main(String[] args)
{
System.out.println("The number of circles created="+Circle.getCount());
Circle c1=new Circle(4,5,2.3)
System.out.println("The number of circles created="+Circle.getCount());
Circle c2=new Circle();
System.out.println("The number of circles created="+Circle.getCount());
System.out.println("Enter dimensions of circle c2");
c2.getCircle();
System.out.println("circle c1=");
c1.showCircle();
System.out.println("its area is "+c1.areaCircle());
System.out.println("its circumference is "+c1.circumCircle());
System.out.println("circle c2=");
c2.showCircle();
System.out.println("its area is "+c2.areaCircle());
System.out.println("its circumference is "+c2.circumCircle());
}
}
Student Class
Write/create a Java class Student to meet the following
specification. - The class should be able to support a 6 digit student
ID/rollno, student name, marks for 5 subjects. You should have
methods to set and get each of the attributes, methods to set and
get marks of the student and methods to calculate the average,
percentage and grade for the student. Write a tester program to
test your class. You should create 2 or 3 students and write code to
test the class
Student Class
State(s): (Attributes)
Roll#, name, marks[5]
Behaviors: (Methods)
setStudent, getStudent, showStudent, calcPercentage, calcGrade,
clacAverage, setMarks, getMarks
class Student int minMarks()
{ {
String rollno; int min=marks[0];
String name; for(int i=1;i<marks.length;i++)
int []marks=new int[5]; if(min>marks[i])
//constructors min=marks[i];
Student(String rn,String nm) return min;
{ }
rollno=rn; int maxMarks()
name=nm; {
int[]mrks={0,0,0,0,0}; int max=marks[0];
marks=mrks; for(int i=1;i<marks.length;i++)
} if(max<marks[i])
Student(String rn,String nm,int[]mrks) max=marks[i];
{ return max;
rollno=rn; }
name=nm; double calcAverage()
marks=mrks; {
} double tmarks=0;
void setMarks(int[]mrks) for(int i=0;i<marks.length;i++)
{ tmarks+=marks[i];
marks=mrks; double avg=(tmarks)/5;
} return avg;
void getMarks() }
{ double calcPercent()
Scanner input=new Scanner(System.in); {
for(int i=0;i<marks.length;i++) double tmarks=0;
{ for(int i=0;i<marks.length;i++)
System.out.print("En[ter marks for subject"+(i+1)+">>"); tmarks+=marks[i];
marks[i]=input.nextInt(); double per=(tmarks/500)*100;
} return per;
} }
char calcGrade()
{
double per=calcPercent();
char grade='E';
if (per<50)
grade='F';
if(per>=50 & per<60)
grade='D';
if(per>=60 & per<70)
grade='C';
if(per>=70 & per<80)
grade='B';
if(per>=80)
grade='A';
return grade;
}
void studentSummary()
{
System.out.println("Name="+name);
System.out.println("Rollno="+rollno);
System.out.println("Marks of the student are");
for(int i=0;i<marks.length;i++)
System.out.print(marks[i]+",");
System.out.println("Minimum marks in the subjects ="+minMarks());
System.out.println("Maximum marks in the subjects ="+maxMarks());
System.out.println("Average marks ="+calcAverage());
System.out.println("Percentage="+calcPercent()+"%");
System.out.println("Grade="+calcGrade());
}
} // closing brace for class body
// main class or application class for student
import java.util.Scanner;
public class MainStudent
{
public static void main(String []args)
{
Student st1=new Student("19cs01","Aslam");
int[] mrks={50,60,70,80,75};
st1.setMarks(mrks);
Student st2=new Student("19CS02","Ahmed");
System.out.println("Enter marks for student st2");
st2.getMarks();
System.out.println("the percentage of student st1 is "+st1.calcPercent()+"%");
System.out.println("and your grade is "+st1.calcGrade());
System.out.println("the percentage of student st2 is "+st2.calcPercent()+"%");
System.out.println("and your grade is "+st2.calcGrade());
System.out.println("Student summary for st1=");
st1.studentSummary();
System.out.println("Student summary for st2=");
st2.studentSummary();
}
}
The Bank Account class
The Circle contains three attributes for each account holder:
(data members)
Balance
Account number
Name
This class contains : (methods)
various constructors to initialize data members
Deposit method to deposit amount
Withdraw method to withdraw amount
Check balance method to determine current balance
Transfer method to transfer amount to another account
infoAccount method to display information of account holder
class BankAccount
{
// These are different for each account
private double balance;
private int accountNumber;
private String name;
// This is a constructor: no return type (void, boolean etc) and has the same name as the class.
public BankAccount(String nm,double intialBalance)
{
balance = intialBalance;
name=nm;
accountNumber = lastAccountNumber + 1;
lastAccountNumber = accountNumber;
System.out.println("Your account has been created");
++count;
}
public void deposit(double depositAmount)
{
balance += depositAmount;
System.out.println("Your current balance is "+balance);
}
public static int getCount()
{
return count;
}
public void withdraw(double withdrawAmount)
{
if (withdrawAmount > balance)
System.out.println("can not withdraw. Insufficient amount");
else
{
balance-=withdrawAmount;
System.out.println("Your balance is "+balance);
}
}
public void checkBalance()
{
System.out.println("Your current balance is "+balance);
}
public void infoAccount()
{
System.out.println("name="+name);
System.out.println("Account number="+accountNumber);
System.out.println("Balance="+balance);
}
public void transfer(BankAccount other, double amount)
{
if(amount<balance)
{
balance-=amount;
other.balance+=amount;
System.out.println("Your balance is "+balance);
}
else
System.out.println("Can not transfer amoutnt. In sufficient amount in your account");
}
} // end of the class
public class BankDemo
{
public static void main(String[] args)
{
System.out.println("The number of accounts have been created are"+BankAccount.getCount());
BankAccount acc1=new BankAccount("Aslam",500);
System.out.println("The number of accounts have been created are"+BankAccount.getCount());
acc1.infoAccount();
BankAccount acc2=new BankAccount("Fareed",300);
System.out.println("The number of accounts have been created are"+BankAccount.getCount());
acc2.infoAccount();
BankAccount acc3=new BankAccount("Faisal",800);
System.out.println("The number of accounts have been created are"+BankAccount.getCount());
acc3.infoAccount();
acc1.deposit(1000);
acc2.withdraw(200);
acc3.transfer(acc2, 500);
acc1.withdraw(2000);
}
}
Stack Class
A stack is a LIFO (Last in first out) system. In stack insertion and
deletion is take place on top of the stack. In stack item stored last
will be retrieved first :
Therefore this class contains data members:
Top // a variable top
Stk[] //an array
This class contains : (methods)
A constructor to initialize top equal to -1
Push method to insert an item on top of the stack
Pop method to delete an item from top of the stack
Show stack method to display contents of the stack
Class for Complex Numbers
A complex number is combination of two parts; a+ib where a is
real part and b is the imaginary part.
Therefore this class contains two data members:
Real
imaginary
This class contains : (methods)
overloaded constructors to initialize complex numbers
getComplex method to get complex number from user
showComplex method to display complex number in the form:
a+jb
Overloaded methods addComplex to add two complex
numbers
Overloaded methods subComplex to perform subtraction
between two complex numbers
The Sphere class
A sphere is a geometrical object in three-dimensional space that
is the surface of a ball (circular objects in three dimensions)
analogous to the circular objects in two dimensions, where a
"circle" circumscribes its "disk").
These are also referred to as the radius and center of the sphere,
respectively. Therefore this class contains data members:
xCenter,yCenter,cCenter // 3D dimensions of the center
Radius // radius of sphere
This class contains : (methods)
overloaded constructors to initialize Sphere
Volume method to calculate the volume of the sphere
getSphere method to get dimensions of sphere from user
showSphere method to display dimensions of sphere object
import java.util.Scanner;
public class DemoCircle
{
public static void main(String[] args)
{
System.out.println("The number of circles created="+Circle.getCount());
Circle c1=new Circle(4,5,2.3)
System.out.println("The number of circles created="+Circle.getCount());
Circle c2=new Circle();
System.out.println("The number of circles created="+Circle.getCount());
System.out.println("Enter dimensions of circle c2");
c2.getCircle();
System.out.println("circle c1=");
c1.showCircle();
System.out.println("its area is "+c1.areaCircle());
System.out.println("its circumference is "+c1.circumCircle());
System.out.println("circle c2=");
c2.showCircle();
System.out.println("its area is "+c2.areaCircle());
System.out.println("its circumference is "+c2.circumCircle());
}
}
Access Control: Data Hiding and Encapsulation
Java provides control over the visibility of variables and
methods.
Encapsulation, safely sealing data within the capsule of
the class Prevents programmers from relying on details
of class implementation, so you can update without
worry
Helps in protecting against accidental or wrong usage.
Keeps code elegant and clean (easier to maintain)
Constructors
A constructor is a special method that contains same name as name
of the class.
Used to initialize the instance variables of an object.
` 1) simple types
` 2) class types
Two corresponding ways of how the arguments are passed to
methods:
1) by value a method receives a cope of the original value;
parameters of simple types
2) by reference a method receives the memory address of the
original value, not the value itself; parameters of class types
Recursion
A recursive method is a method that calls itself:
2D Point Class
State(s):
X,y
Behaviors:
translate,scale,disance
3D Box class
Rectangle Class
State(s):
State(s):
Length, width, height
Length, width
Behaviors:
Behaviors:
Set, get,volume
Set,get, Area