Previously, you studied about creating classes and creating objects from those classes. But the class we took for an example contained only one method. Actually, the classes contain attributes and methods. Attributes are actually variables that reside in the class and are particular to the class and methods are methods which perform actions on those attributes and may or may not return a value.
Now let’s create a new java project and create a class named rectangle in it:
Now let’s add attributes to our class. We will add a length attribute and a width attribute to our class. Remember that attributes are simple variables and it will look like this:
Now let’s add methods to our class. One method will find area and the other will find the perimeter of the rectangle.
public int findArea()
public int findPerimeter()
*The length and width variables we used in the methods are actually the class attributes(variables) we defined above
The whole class will now look like this:
Now let’s create an object of your new class and set the length and width for the object. Accessing the attributes of a class is same as accessing its methods. We use the attribute and the object name separated by period.
Now let’s use the findArea and findPerimeter methods to find and display the area and perimeter of the rectangle object.
An answer to the question from the previous lesson: We can use static methods even without creating object of the class. So why are’nt all the methods static? The answer is that static methods can not access the non-static attributes of the class. For example, if we declared the findArea method static in the above Rectangle class, it would not be able to access the non-static length and width of the rectangle. Attributes can also be declared static. We will learn more about static and non static methods and variables in a separate lesson.
- Write a square class. It will have the length of one side of the square as an attribute and two methods to find area and perimeter. Then implement the square class by creating objects from it and setting the attributes and calling its methods.
- Create a cuboid class with length, width and height as attributes and two methods to find volume and surface area. Implement the cuboid class same as in the previous question.