Lab 06 - Classes, Objects & Constructors: Objective
Lab 06 - Classes, Objects & Constructors: Objective
Class
A class is a user defined blueprint or prototype from which objects are created. It represents the set of
properties or methods that are common to all objects of one type. In general, class declarations can
include these components, in order:
Constructors are used for initializing new objects. Fields are variables that provides the state of the class
and its objects, and methods are used to implement the behavior of the class and its objects.
There are various types of classes that are used in real time applications such as nested classes,
anonymous classes, lambda expressions.
Object
It is a basic unit of Object-Oriented Programming and represents the real life entities. A typical Java
program creates many objects, which as you know, interact by invoking methods. An object consists of :
Example
// Class Declaration
// method 1
public String getName()
{
return name;
}
// method 2
public String getBreed()
{
return breed;
}
// method 3
public int getAge()
{
return age;
}
// method 4
public String getColor()
{
return color;
}
There are four ways to create objects in java.Strictly speaking there is only one way(by
using new keyword),and the rest internally use new keyword.
Using new keyword: It is the most common and general way to create object in java. Example:
// creating object of class Test
Test t = new Test();
Lab Tasks:
Task 1:
Create a class named 'Student' with String variable 'name' and integer variable 'roll_no'. Assign the value
of roll_no as '2' and that of name as "John" by creating an object of the class Student.
Task 2:
Write a program to print the area and perimeter of a triangle having sides of 3, 4 and 5 units by creating
a class named 'Triangle' without any parameter in its constructor.
Task 3:
Write a program to print the area of two rectangles having sides (4,5) and (5,8) respectively by creating
a class named 'Rectangle' with a method named 'Area' which returns the area and length and breadth
passed as parameters to its constructor.
Task 4:
Write a program to print the area of a rectangle by creating a class named 'Area' taking the values of its
length and breadth as parameters of its constructor and having a method named 'returnArea' which
returns the area of the rectangle. Length and breadth of rectangle are entered through keyboard.
Lab Tasks:
Explain with the examples this keyword uses.