Introduction To Objects Classes
Introduction To Objects Classes
OO Programming Concepts Declaring and Creating Objects Constructors Modifiers (public, private)
Object
represents
an entity in the real world that can be distinctly identified. it has a unique identity, state and behaviors.
the state of an object is represented by data fields (also known as properties) The behavior of an object is defined by as set of methods.
is
an instance of a class
Class
is
a template or blueprint that defines what an objects data and methods will be. one can create many instances of a class. Creating an instance is referred to as instantiation. is a construct that defines objects of the same type.
OO Programming Concepts
An object data field 1 ... data field n method 1 ... method n Behavior State
Method findArea A Circle object Data Field radius = 5
Class Declaration
class Circle { double radius = 1.0; double findArea() { return radius*radius*3.14159; }
Declaring Objects
ClassName objectName;
Example:
Circle myCircle;
Creating Objects
objectName = new ClassName();
Example:
myCircle = new Circle();
Example:
Circle myCircle = new Circle();
Before: i j 1 2
After: i j 2 2
Accessing Objects
Referencing
objectName.data
myCircle.radius
Referencing
objectName.method
myCircle.findArea()
Demonstrate creating objects, accessing data, and using methods. Sample: TestCircle.java
Constructors
is
a special kind of method are invoked when a new object is created. are designed to perform initializing actions such as initializing the data fields of objects. are used to construct objects, has exactly the same name as the defining class. can be overloaded (multiple constructors with the same name but different signatures)
Constructors
Circle(double r) { radius = r; } Circle() { radius = 1.0; } myCircle = new Circle(5.0);
Discuss the role of constructors and use them to create objects. Sample: TestCircleWithConstructors.java
TestCircle1.java Circle1.java
by reference by value
public
The class, data, or method is visible to any class in any package.
private
The data or methods can be accessed only by the declaring class. The getter and setter accessor methods are used to read and modify private properties.
TestCircleWithPrivateModifier.java
Exercise:
Write a class named Rectangle to represent rectangles. The data fields are height and width declared as private. You need to provide the assessor methods for the properties and a method findArea() for computing the area of the rectangle. Write a client program to test the class Rectangle. In the client program, create two Rectangle objects. Assign any widths and heights to the two objects. Display
both object's properties and find their areas. Call your setter method that would update the width and height of the rectangle by 20%.
Sample Output: