Syntax
to create an Object
ClassName
objectName = new ClassName();
Example
Person
personA = new Person();
Here
Person is the class name
personA
is the object created for the class Person.
Once
the class is defiined, you can create any number of objects to it.
Person
personB = new Person();
Person
personC = new Person();
How
to access properties of an object
java
provides '.' opertor to access th properties of an object.
Syntax:
objectName.propertyName = value;
Example
personA.height = 6;
personB.height = 5.5;
How
to call the behaviors
Just
like how you are accessing properties, you can call the behaviours.
Syntax
objectName.behavior();
Example
personA.getHeight();
personB.getHeight();
Complete
Working Example of Person class
class Person{ float height, weight; String color, country; float getHeight(){ return height; } float getWeight(){ return weight; } String getColor(){ return color; } String getCountry(){ return country; } public static void main(String args[]){ /* Declaring two person objects */ Person personA = new Person(); Person personB = new Person(); /* Setting properties for personA object */ personA.height = 6; personA.weight = 75; personA.color = "White"; personA.country = "India"; /* Setting properties for personB object */ personB.height = 5.5f; personB.weight = 76; personB.color = "Black"; personB.country = "America"; /* Calling the behaviors and printing the details of personA */ System.out.println("PersonA Height is " + personA.getHeight()); System.out.println("PersonA Weight is " + personA.getWeight()); System.out.println("PersonA color is " + personA.getColor()); System.out.println("PersonA country is " + personA.getCountry()); System.out.println(); /* Calling the behaviors and printing the details of personB */ System.out.println("PersonB Height is " + personB.getHeight()); System.out.println("PersonB Weight is " + personB.getWeight()); System.out.println("PersonB color is " + personB.getColor()); System.out.println("PersonB country is " + personB.getCountry()); } }
Output
PersonA Height is 6.0 PersonA Weight is 75.0 PersonA color is White PersonA country is India PersonB Height is 5.5 PersonB Weight is 76.0 PersonB color is Black PersonB country is America
No comments:
Post a Comment