You are on page 1of 14

1) This example shows how to define a specified class using the problem

statement and the Class diagram.


Following things are illustrated with this example:
a) Default and parameterized constructor
b) How to determine the private/public access specifiers for
attributes and methods (getters, setters and business behavior)
c) Naming the methods (camel case notation).

Question:
Define Car class as per the diagram given below.
Allow creation of Car objects
a) Without passing any values
b) By passing exactly the brandName and modelNo

Accelerate method increases the speed by 5 each time it is called, and applyBrakes
sets the speed to zero.
Also define all the getters and setters for this class.

Solution: (below code may by pasted in Dr. Java editor and file saved as Car.java)
public class Car
{
// All attributes in the diagram are indicated by '-', which means
private attributes
private String brandName;
private String modelNo;
private double price;
private int speed;

// Default constructor (i.e. without passing any values)


Car()
{

// Parameterized constructor (i.e. by passing exactly brandName and


modelNo)
Car(String bName, String mNumber)
{
this.brandName = bName;

TCS Internal
this.modelNo = mNumber;
}

// Defining all Getters (always define as public, use Camel case


notation)
public String getBrandName() { return brandName; }
public String getModelNo() { return modelNo; }
public double getPrice() { return price; }
public int getSpeed() { return speed; }

// Defining all Setters (always define as public, use Camel case


notation)
public void setBrandName(String newBrandName) {this.brandName =
newBrandName;}
public void setModelNo(String newModelNo) {this.modelNo = newModelNo;}
public void setPrice(double newPrice) {this.price = newPrice;}
public void setSpeed(int newSpeed) {this.speed = newSpeed;}

// Business Behaviors
// All behaviors in the diagram are indicated by '+', which means
public methods

public void accelerate()


{
this.speed = speed + 5;
}

public void applyBrakes()


{
this.speed = 0;
}

Tests: (can be run in Dr. Java - interactions window)

Car c1 = new Car()

Car myCar = new Car("Tata", "Nano")

myCar.getBrandName()
"Tata"

myCar.getModelNo()
"Nano"

myCar.getPrice()
0.0

TCS Internal
myCar.getSpeed()
0

myCar.setPrice(125000)
myCar.getPrice()
125000.0

myCar.setSpeed(40)
myCar.getSpeed()
40

myCar.accelerate()
myCar.getSpeed()
45

myCar.accelerate()
myCar.getSpeed()
50

myCar.applyBrakes()
myCar.getSpeed()
0

TCS Internal
2) This example demonstrates Class Relationship – Inheritance
Following things are illustrated with this example:
a) Notation for Inheritance relationship
b) How to define Base class (Parent class)
c) How to define Derived class (Child class)
d) How to access Base class members in Derived class objects

Question:
Define classes as per the diagram given below.
Allow creation of Laptop and PC objects by only passing all required attribute values.
Laptop or PC objects when created, will always have isOn attribute set as false.

Switch ON and OFF behaviors simply change the value of isOn attribute to True and
False respectively. Charge method simply adds 1 hr of battery life every time it is
called.

Solution: (below code may by pasted in Dr. Java editor and file saved as Computer.java)
class Computer
{
// This is the Base Class

// Defining attribues as given in Class diagram with appropriate access


specifiers
public String make;
private String procName;
private int ram;

TCS Internal
private int hdd;
private boolean isOn;

// Constructor
Computer(String make, String procName, int ram, int hdd)
{
this.make = make;
this.procName = procName;
this.ram = ram;
this.hdd = hdd;
this.isOn = false;
}

// Define all Getters and Setters (as public methods)


// Not shown for all in this sample solution
public String getProcName() {return procName;}
public boolean getIsOn(){return isOn;}

public void setProcName(String newProcName){this.procName =


newProcName;}

// Defining methods as given in Class diagram with appropriate access


specifiers
public void switchOn(){isOn = true;}
public void switchOff(){isOn = false;}
}

class Laptop extends Computer


{
// This is the first derived class

// Defining attribues as given in Class diagram with appropriate access


specifiers
private int remainingBatteryLife;

// Constructor
Laptop(String make, String procName, int ram, int hdd, int
remainingBatteryLife)
{
super(make, procName, ram, hdd);
this.remainingBatteryLife = remainingBatteryLife;
}

// Define all Getters and Setters (as public methods)


public int getRemainingBatteryLife() {return remainingBatteryLife;}

public void setRemainingBatteryLife(int newLife)


{this.remainingBatteryLife = newLife;}

// Defining methods as given in Class diagram with appropriate access


specifiers

TCS Internal
public void charge()
{
this.remainingBatteryLife = this.remainingBatteryLife + 1;
}

}
class PC extends Computer
{
// This is the second derived class

// Defining attribues as given in Class diagram with appropriate access


specifiers
private String displayType;

// Constructor
PC(String make, String procName, int ram, int hdd, String dType)
{
super(make, procName, ram, hdd);
displayType = dType;
}

// Define all Getters and Setters (as public methods)


public String getDisplayType() {return displayType;}

public void setDisplayType (String newType) {this.displayType=


newType;}

// Defining methods as given in Class diagram with appropriate access


specifiers
// None for this class

Tests: (can be run in Dr. Java - interactions window)

Computer c1 = new Laptop("Dell","AMD",512, 160, 3)


c1.make // can be directly accessed since public
"Dell"

c1.getProcName()
"AMD"

c1.getIsOn()
false

c1.setProcName("Intel")
c1.getProcName()
"Intel"

TCS Internal
c1.switchOn()
c1.getIsOn()
true

c1.switchOff()
c1.getIsOn()
false

// The below typecasting could be avoided if we create c1 as follows:


// Laptop c1 = new Laptop("Dell","AMD",512, 160, 3)
((Laptop)c1).charge()
((Laptop)c1).getRemainingBatteryLife()
4

((Laptop)c1).charge()
((Laptop)c1).getRemainingBatteryLife()
5

Computer c2 = new PC("Compaq","PIV",256, 200, “LCD”)


c2.make
"Compaq"

c2.getProcName()
"PIV"

// The below typecasting could be avoided if we create c2 as follows:


// PC c2 = new PC("Compaq","PIV",256, 200, “LCD”)
((PC)c2).getDisplayType()
“LCD”

((PC)c2).setDisplayType("CRT")
((PC)c2).getDisplayType()
"CRT"

TCS Internal
3) This example demonstrates Class Relationship – Aggregation
Following things are illustrated with this example:
a) Aggregation is also a form of association, wherein a part-of
relationship exists, i.e. the container class may contain objects
of another class, without being responsible for either its
creation or destruction.
b) Notation used for showing Aggregation relationship between
two classes

Question:
Define classes as per the diagram given below.
Allow creation of Organization and Employee objects only by passing their
respective names. By default, any new employee gets a designation of “Trainee” and
has an initial leave balance of 2 days.
Any employee is allowed to apply leave as per the leave balance available. If
employee tries to avail more leave than his/her balance, display appropriate message
to the employee and do not process leave.
When adding employees, increment the organization strength by 1 after adding the
employee to the list.

Solution: (below code may by pasted in Dr. Java editor and file saved as
Organization.java)
import java.util.ArrayList;

public class Organization


{
// Attributes
private String name;
private int strength;
private ArrayList<Employee> empList = new ArrayList<Employee>();

// Constructor
Organization(String name)
{
this.name = name;
this.strength = 0;
}

TCS Internal
// Getters
public String getName() {return name;}
public int getStrength(){return strength;}
public ArrayList<Employee> getEmpList() {return empList;}

// Setters
public void setName(String newName){name = newName;}
public void setStrength(int newStrength){strength = newStrength;}
public void setEmpList(ArrayList<Employee> newList) {empList =
newList;}

// Business Behaviors (employee object is directly being passed, and is


not being created in this class)
public void addEmp(Employee e)
{
empList.add(e);
strength = strength + 1;
}
}

class Employee
{
// Attributes
private String name;
private String designation;
private int leaveBalance;

// Constructor
Employee(String name)
{
this.name = name;
designation = "Trainee";
leaveBalance=2;
}

// Getters
public String getName(){return name;}
public String getDesignation(){return designation;}
public int getLeaveBalance(){return leaveBalance;}

// Setters
public void setName(String newName){name = newName;}
public void setDesignation(String newDesg){designation = newDesg;}
public void setLeaveBalance(int newBal){leaveBalance = newBal;}

// Business Behaviors
public void applyLeave(int noOfDays)
{
if (noOfDays <= leaveBalance)
{
leaveBalance = leaveBalance - noOfDays;
}
else

TCS Internal
{
System.out.println("Sorry, you do not have sufficient leave
balance.");
}
}
}

Tests: (can be run in Dr. Java - interactions window)


Organization myOrg = new Organization("TCS")
myOrg.getName()
"TCS"

myOrg.getStrength()
0

myOrg.getEmpList().size()
0

myOrg.setStrength(2000)
myOrg.getStrength()
2000

Employee e1 = new Employee ("Manoj")


e1.getName()
"Manoj"

e1.getDesignation()
"Trainee"

e1.getLeaveBalance()
2

e1.setLeaveBalance(5)
e1.getLeaveBalance()
5

myOrg.addEmp(e1)
myOrg.getEmpList().size()
1

myOrg.getStrength()
2001

myOrg.getEmpList().get(0).getName()
"Manoj"

TCS Internal
myOrg.getEmpList().get(0).applyLeave(10)
Sorry, you do not have sufficient leave balance.

myOrg.getEmpList().get(0).applyLeave(3)
myOrg.getEmpList().get(0).getLeaveBalance()
2

TCS Internal
4) This example demonstrates Class Relationship – Composition
Following things are illustrated with this example:
a) Composition is a stronger form of aggregation, wherein a part-
of relationship exists, i.e. the container class contains objects
of another class, and is also responsible for its creation or
destruction.
b) Notation used for showing Composition relationship between
two classes

Question:
Define classes as per the diagram given below.
Allow creation of Building object without passing any parameter, whereas Room
object can only be created by passing the length and width of the room. For newly
added rooms, the AC is not installed initially.

In Room class, the addAC method will simply set the hasAC flag to true.
In Building class, the addRoom method will add a room to roomList and also will
increment the total room count by 1.

Solution: (below code may by pasted in Dr. Java editor and file saved as Building.java)
import java.util.ArrayList;

public class Building


{
//Attributes
private int noOfFloors;
private int totalRooms;
private ArrayList<Room> roomList = new ArrayList<Room>();

//Constructor (creating one room whenever building object is created to


satisfy 1..* relationship shown in diagram)
Building()
{
addRoom(14, 20);
}

//Getters
public int getNoOfFloors(){return noOfFloors;}

TCS Internal
public int getTotalRooms(){return totalRooms;}
public ArrayList<Room> getRoomList() {return roomList;}

//Setters
public void setNoOfFloors(int newNumber){noOfFloors = newNumber;}
public void setTotalRooms(int newRooms){totalRooms = newRooms;}
public void setRoomList(ArrayList<Room> newRoomList){roomList =
newRoomList;}

//Behaviors
public void addRoom (int len, int width)
{
Room r = new Room (len, width);
roomList.add(r);
totalRooms = totalRooms + 1;
}

class Room
{
//Attributes
private int len;
private int width;
private boolean hasAC;

//Constructor
Room(int len, int width)
{
this.len = len;
this.width = width;
hasAC = false;
}

//Getters
public int getLen(){return len;}
public int getWidth(){return width;}
public boolean getHasAC(){return hasAC;}

//Setters
public void setLen(int newLen){len = newLen;}
public void setWidth(int newWidth){width = newWidth;}
public void setHasAC(boolean newHasAC){hasAC = newHasAC;}

//Business behaviors
public void addAC()
{
hasAC = true;
}
}

TCS Internal
Tests: (can be run in Dr. Java - interactions window)

Building b = new Building()

b.getNoOfFloors()
0

b.getTotalRooms()
1

b.getRoomList()
[Room@59c8b5]

b.setNoOfFloors(2)
b.getNoOfFloors()
2

b.addRoom(10, 12)

b.getTotalRooms()
2

b.getRoomList()
[Room@59c8b5, Room@916f80]

b.getRoomList().get(1).getLen()
10

b.getRoomList().get(1).getWidth()
12

b.getRoomList().get(1).getHasAC()
false

b.getRoomList().get(1).addAC()
b.getRoomList().get(1).getHasAC()
true

TCS Internal

You might also like