Classes and Objects
Naorem Karline Singh
Drawbacks of procedural programming
languages
1) programs are difficult to debug – little restriction to data access
2) programs are hard to understand – many variables have global scope
3) programs are hard to reuse – data/functions are mutually dependent
4) little support for developing and comprehending really large programs
What is an Object?
Real world objects are things that have:
1) state
2) behavior
Example: your dog:
1) state – name, color, breed, sits?, barks?, wages tail?, runs?
2) behavior – sitting, barking, waging tail, running
A software object is a bundle of variables (state) and methods (operations).
What is an Class?
A class is a blueprint that defines the variables and methods common to all
objects of a certain kind.
Example: ‘your dog’ is a object of the class Dog.
An object holds values for the variables defines in the class.
An object is called an instance of the Class
Classes vs Objects
1) operations: changeGears, brake, changeCadence
2) variables: currentSpeed, currentCadence, currentGear
3) static variable: numberOfGears - It holds the same value for all objects
of the class.
Object-Oriented Concepts
Three main concepts:
1) encapsulation
2) inheritance
3) polymorphism
Encapsulation
• Enclose data inside an object.
• Along with data, include operations on this data.
• Data cannot be accessed from outside except through the operations.
• Provides data security and facilitates code reuse.
• Operations provide the interface - internal state can change without affecting the user as
long as the interface does not change.
Encapsulation
Inheritance
Features:
1) a class obtains variables and methods
from another class
2) the former is called subclass, the latter
super-class
3) a sub-class provides a specialized
behavior with respect to its super-class
4) inheritance faciliates code reuse and
avoids duplication of data
Polymorphism
Polymorphism = many different (poly) forms of objects that share a common interface
respond differently when a method of that interface is invoked.
Polymorphism is enabled by inheritance:
1) a super-class defines an interface that all sub-classes must follow
2) it is up to the sub-classes how this interface is implemented; a subclass may override
methods of its super-class
Therefore, objects from the classes related by inheritance may receive the same requests
but respond to such requests in their own ways.
Polymorphism
Polymorphism
Objects
Everything in Java is an object.
Well ... almost.
Object lifecycle:
1) creation
2) usage
3) destruction
Object Creation
A variable s is declared to refer to the objects of type/class String:
String s;
The value of s is null; it does not yet refer to any object.
A new String object is created in memory with initial “abc” value:
String s = new String(“abc”);
Now s contains the address of this new object.
Object Usage
String s = new String(“abc”);
What can you do with the object addressed by s?
1) Check the length: s.length() == 3
2) Return the substring: s.substring(2)
3) etc.
Depending what is allowed by the definition of String.
Object Usage
String s1 = new String(“abc”);
String s2;
Assignment copies the address, not value:
s2 = s1;
Now s1 and s2 both refer to one object. After
s1 = null;
s2 still points to this object.
Object Usage
Two variables, two objects:
String s1 = new String(“abc”);
String s2 = new String(“abc”);
s1 and s2 objects have initially the same values:
s1.equals(s2) == true
But they are not the same objects:
(s1 == s2) == false
They can be changed independently of each other.
Object Usage
One variable, two objects:
String s = new String(“abc”);
s = new String(“cba”);
The “abc” object is no longer accessible through any variable.
Object Destruction
A program accumulates memory through its execution.
Two mechanism to free memory that is no longer need by the program:
1) manual – done in C/C++
2) automatic – done in Java
In Java, when an object is no longer accessible through any variable, it is
eventually removed from the memory by the garbage collector.
Garbage collector is parts of the Java Run-Time Environment.
Class outline:
1) class definition
a) attributes
b) methods
c) constructors
2) method overloading
3) method communication
a) passing arguments
b) returning results
4) recursive methods
5) arrays as object
6) static components
7) nested and internal classes
Class
A basis for the Java language.
Each concept we wish to describe in Java must be included inside a class.
A class defines a new data type, whose values are objects:
1) a class is a template for objects
2) an object is an instance of a class
Class Definition
A class contains a name, several variable declarations (instance variables)
and several method declarations. All are called members of the class.
General form of a class:
class classname {
type instance-variable-1;
…
type instance-variable-n;
type method-name-1(parameter-list) { … }
type method-name-2(parameter-list) { … }
…
type method-name-m(parameter-list) { … }
}
Example: Class
A class with three variable members:
class Box {
double width;
double height;
double depth;
}
A new Box object is created and a new value assigned to its width variable:
Box myBox = new Box();
myBox.width = 100;
Example: Class
class BoxDemo {
public static void main(String args[]) {
Box mybox = new Box();
double vol;
mybox.width = 10;
mybox.height = 20;
mybox.depth = 15;
vol = mybox.width * mybox.height * mybox.depth;
System.out.println("Volume is " + vol);
}
}
Compilation and Execution
Place the Box class definitions in file Box.java:
class Box { … }
Place the BoxDemo class definitions in file BoxDemo.java:
class BoxDemo {
public static void main(…) { … }
}
Compilation and execution:
> javac BoxDemo.java
> java BoxDemo
Variable Independence 1
Each object has its own copy of the instance variables: changing the variables of one object has no effect on the
variables of another objects
Consider this example:
class BoxDemo2 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.width = 10;
mybox1.height = 20;
mybox1.depth = 15;
Variable Independence 2
mybox2.width = 3;
mybox2.height = 6;
mybox2.depth = 9;
vol = mybox1.width * mybox1.height * mybox1.depth;
System.out.println("Volume is " + vol);
vol = mybox2.width * mybox2.height * mybox2.depth;
System.out.println("Volume is " + vol);
}
}
What are the printed volumes of both boxes?
Declaring objects
Obtaining objects of a class is a two-stage process:
1) Declare a variable of the class type:
Box myBox;
The value of myBox is a reference to an object, if one exists, or null. At this moment, the value of
myBox is null.
2) Acquire an actual, physical copy of an object and assign its address to the variable. How to do this?
Operator new
Allocates memory for a Box object and returns its address:
Box myBox = new Box();
The address is then stored in the myBox reference variable.
Box() is a class constructor - a class may declare its own constructor or rely on the default
constructor provided by the Java environment.
Memory Allocation
Memory is allocated for objects dynamically.
This has both advantages and disadvantages:
1) as many objects are created as needed
2) allocation is uncertain – memory may be insufficient
Variables of simple types do not require new:
int n = 1;
In the interest of efficiency, Java does not implement simple types as objects. Variables of
simple types hold values, not references.
Methods
General form of a method definition:
type name(parameter-list) {
… return value; …
}
Components:
1) type - type of values returned by the method. If a method does not return any value, its
return type must be void.
2) name is the name of the method
3) parameter-list is a sequence of type-identifier lists separated by commas
4) return value indicates what value is returned by the method.
Example: Methods 1
Classes declare methods to hide their internal data structures, as well as for their own
internal use:
Within a class, we can refer directly to its member variables:
class Box {
double width, height, depth;
void volume() {
System.out.print("Volume is ");
System.out.println(width * height * depth);
}
}
Example: Methods 2
When an instance variable is accessed by code that is not part of the class in which that
variable is defined, access must be done through an object:
class BoxDemo3 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
mybox1.width = 10; mybox2.width = 3;
mybox1.height = 20; mybox2.height = 6;
mybox1.depth = 15; mybox2.depth = 9;
mybox1.volume();
mybox2.volume();
}
}
Value-Returning: Methods 1
The type of an expression returning value from a method must agree with the return type of
this method:
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
}
Value-Returning: Methods 2
class BoxDemo4 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.width = 10;
mybox2.width = 3;
mybox1.height = 20;
mybox2.height = 6;
mybox1.depth = 15;
mybox2.depth = 9;
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}
Parameterized Method
Parameters increase generality and applicability of a method:
1) method without parameters
int square() { return 10*10; }
2) method with parameters
int square(int i) { return i*i; }
Parameter: a variable receiving value at the time the method is invoked.
Argument: a value passed to the method when it is invoked.
Example: Parameterized Method 1
class Box {
double width;
double height;
double depth;
double volume() {
return width * height * depth;
}
void setDim(double w, double h, double d) {
width = w; height = h; depth = d;
}
}
Example: Parameterized Method 2
class BoxDemo5 {
public static void main(String args[]) {
Box mybox1 = new Box();
Box mybox2 = new Box();
double vol;
mybox1.setDim(10, 20, 15);
mybox2.setDim(3, 6, 9);
vol = mybox1.volume();
System.out.println("Volume is " + vol);
vol = mybox2.volume();
System.out.println("Volume is " + vol);
}
}