Java10: Class and Object
Object is real life entity that has attributes and behaviors and has unique identity. In object oriented programming, a program is designed based on objects that take part in a system.
To use object in a program, first we have to define a class. Class is a blueprint that define how a object has to be created. Without a class, we can't create an object.Defining a Class
To define a class
class ClassName{ // attributes and behaviors. }
The class keyword indicates the begining of the class definition. It is followed by the class name. As a convention, class name begins with capital letter and has no space. The the curly braket contains the attribute and behaviors of the class.
Example
class Circle{
double radius;
String color;
double calculateArea(){
double area;
area = Math.PI * Math.pow(this.radius, 2);
return area;
}
void info(){
System.out.println("Color : " + this.color);
System.out.println("Radius : " + this.radius);
}
}
Creating the Object
To create an object, we need to use the new keyword. The syntax is: d
ClassName objectReference = new ClassName(parameters);
class CircleDemo{
public static void main(String[] args){
Circle cir1 = new Circle();
}
}
The name of the class is Circle
. and the object reference variable is cir1
. Then, after the new keyword, we specify the name of the constructor, in this case it's Circle()
. This will create the circle object and its reference is assigned to cir1
.
Accessing property
To access the properties of the object, use the dot operator. For example
class CircleDemo{
public static void main(String[] args){
Circle cir1 = new Circle();
cir1.radius = 3.5;
double area = cir1.calculateArea();
System.out.println("The area of the circle is " + area);
}
}
Constructor
When we create an object, the constructor of the class is called. It is a special method whose main purpose is to create and initialize the object. A constructor has same name as the class name. All classes has constructor eventhough we don't provide one.
class ClassName{ ClassName(parameters){ // codes } }
A constructor do not have return type as it does not return as value. The constructor initialize the object by assigning initial value to the attributes of the object.
class Circle{
double radius;
String color;
Circle(double radius, double color){
this.radius = radius;
this.color = color;
}
double calculateArea(){
double area;
area = Math.PI * Math.pow(this.radius, 2);
return area;
}
void info(){
System.out.println("Color : " + this.color);
System.out.println("Radius : " + this.radius);
}
}
The constructor above allow us to create object as follows:
class CircleDemo{
public static void main(String[] args){
Circle cir1 = new Circle(3.5, "red");
cir1.info();
}
}
Output
Color: red Radius : 3.5
A post by Cuber
Comments
Post a Comment