0% found this document useful (0 votes)
88 views

V.2.0. - OOP in Java - Get Your Hands Dirty With Code

The document discusses getters and setters in Java object-oriented programming. It explains that getters retrieve field values and setters set field values. A code example shows a Car class with private fields and public getters and setters to access the fields. The document notes that encapsulation through private fields and public accessors hides implementation details and protects data from being modified directly.

Uploaded by

Iftekharul Islam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
88 views

V.2.0. - OOP in Java - Get Your Hands Dirty With Code

The document discusses getters and setters in Java object-oriented programming. It explains that getters retrieve field values and setters set field values. A code example shows a Car class with private fields and public getters and setters to access the fields. The document notes that encapsulation through private fields and public accessors hides implementation details and protects data from being modified directly.

Uploaded by

Iftekharul Islam
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

OOP in Java - Get your hands dirty with code

(Don’t just copy and paste the codes, type the codes like there’s no
tomorrow)

Getters and Setters

 You might prefer to call them Accessors and Mutators, but Getters and
Setters fits the Java naming convention.
 One of the basic goals of object-oriented programming is to hide the
implementation details of a class inside from outside world.
 A get accessor (also called a getter) is a method that retrieves a field value,
whereas a set accessor (setter) is a method that sets a field value. Instance
variable values, usually.
 If the field is named “color”, for example, the getter and setter methods are
named “getColor” and “setColor”.

class Car {
String brand;
String color;
boolean sunRoof;

String getBrand() {
return brand;
}

void setBrand(String brand) {


this.brand = brand;
}

String getColor() {
return color;
}

void setColor(String color) {


this.color = color;
}

boolean hasSunRoof() {
return sunRoof;
}

void setSunRoof(boolean sunRoof) {


this.sunRoof = sunRoof;
}

String beeping() {
if (brand.equals("BMW")) {
return "Beep Beep...I am BMW!";
} else if (brand.equals("Mercedes Benz")) {
return "Beep Beep...I am Mercedes Benz!";
} else {
return "Beep Beep...I am Poor Brand!";
}
}
}

Here we are, just humming along without a care in the world leaving our data
out there for anyone to see and even touch i.e. we are exposing our data! We
are leaving our instance variables exposed!

Exposed means reachable with the dot (.) operator, as in:


mercedes.color = "black";
mercedes.brand = "Mercedes Benz";

Suppose, you have cat. Which have a height.

For example: myCat.height = 25; (exposed to the world already!)

In the hands of the wrong person, a reference variable (in here, “myCat”) is
quite a dangerous weapon. They can flat your cat like below:

myCat.height = 0; (a cat without a height (Flat Cat)!)

So, how can we hide our data?

By using Encapsulation. “Encapsulation” that protects our data and protects


our right to modify our implementation later. OK, so how exactly do we hide the
data? With the “public” and “private” access modifiers.

As a general rule, you should avoid creating “public” fields. Instead, you can
make all your fields (instance variables) “private”. Then you can selectively
grant access to the data those fields contain by adding to the class special
methods called accessors.

 Mark instance variables “private”.


 Mark getters and setters “public”.

Note: We will not talk about access modifiers (public, private, protected, default)
in details now.
class Car {
private String brand;
private String color;
private boolean sunRoof;

public String getBrand() {


return brand;
}

public void setBrand(String brand) {


this.brand = brand;
}

public String getColor() {


return color;
}

public void setColor(String color) {


this.color = color;
}

public boolean hasSunRoof() {


return sunRoof;
}

public void setSunRoof(boolean sunRoof) {


this.sunRoof = sunRoof;
}

String beeping() {
if (brand.equals("BMW")) {
return "Beep Beep...I am BMW!";
} else if (brand.equals("Mercedes Benz")) {
return "Beep Beep...I am Mercedes Benz!";
} else {
return "Beep Beep...I am Poor Brand!";
}
}
}

Why on earth we are not just make brand, color and sunRoof as public
and skip the accessors?

If all your accessors do is set and return the values, without doing any data
validation or other processing, you may as well skip them. The point of making
your fields “private” is to carefully control access to them. If you’re going to use
accessors for all your fields, you might as well make the fields “public”. Instead,
carefully consider which fields really should be accessible to the outside world
(another class) — and provide accessors only for those fields that really need
them.
class CarRunner {
public static void main(String[] args) {
Car bmw = new Car();
bmw.setBrand("BMW");
bmw.setColor("White");
bmw.setSunRoof(true);

Car mercedes = new Car();


mercedes.setBrand("Mercedes Benz");
mercedes.setColor("Black");
mercedes.setSunRoof(true);

System.out.println("I have a " + bmw.getBrand() + ", it is " + bmw.getColor()


+ " and it has a sun roof which is = " + bmw.hasSunRoof());
System.out.println("I have a " + mercedes.getBrand() + ", it is " +
mercedes.getColor() + " and it has a sun roof which is = " + mercedes.hasSunRoof());
}
}

CODE Exercise

Create a class that can calculate area of a triangle.


1
Formula: area of a triangle = 2 ∗ 𝑏𝑎𝑠𝑒 ∗ ℎ𝑒𝑖𝑔ℎ𝑡

Follow the steps to do this:

Steps to follow:

A) Define class with


2 member variables (base, height) and 3 methods (getArea, setHeight, setBase)

class Triangle {
float base;
float height;

float getArea() {
return (this.base * this.height) / 2;
}

void setBase(float base) {


this.base = base;
}

void setHeight(float height) {


this.height = height;
}
}

B) Write code to calculate the area of a triangle which has base 3cm and height
4cm

class triangleRunner {
public static void main(String[] args) {
Triangle triangleOne = new Triangle();

triangleOne.setBase(3);
triangleOne.setHeight(4);
System.out.println(triangleOne.getArea());
}
}

How many square centimeter (sqcm) do you get?

By the way, what’s wrong with my code?

Can you fix it or not?

If you can make the above code working please create below classes:

A) A Rectangle class to calculate the area of a rectangle


Your table top is 2 ft. length and 1 ft. width. Using your class, calculate the
area of the table top (Formula: area of a rectangle = 𝑤𝑖𝑑𝑡ℎ ∗ 𝑙𝑒𝑛𝑔𝑡ℎ)

B) A Circle class to calculate the area of a circle


If the radius of a circle is 2 cm, what is its area? Calculate using your class
(Formula: area of a circle = 𝜋𝑟 2 )
r = radius of the circle

C) The volume of a rectangle can be calculated by using following formula


(Formula: volume of a rectangle = 𝑙𝑒𝑛𝑔𝑡ℎ ∗ 𝑤𝑖𝑑𝑡ℎ ∗ ℎ𝑒𝑖𝑔ℎ𝑡
How do you plan / design your class to do this?

Note: length, width, height shouldn’t be negative and zero.

CODE Exercise

Build your concept

 Now you have the idea of Class


 You have the idea of Object

(A) Think and write about 3 different Classes.


For example: Car, Fruit, and Course

(B) Think and write 2 members (fields) of each class.

For example: Car: door, seat; Fruit: color, taste; Course: title, credit

(C) Think and write 1 method of each class.

For example: Car: drive(); Fruit: isSweet(); Course: hasOffered()

Now, create the classes.

Access your class’s fields with getters and setters.

Don’t forget to encapsulate your methods.

CODE Exercise

Let’s return to the “User” class that we developed in the previous chapters. This is
the User class:
class User {
// your code goes here
}

(A) Create methods to set the “firstName” and “lastName” property value.
Remember to use the right access modifier.

(B) Now, create a method “getFullName” to return the “firstName” and “lastName”.

(C) Create a new user object with the name of “anUser”, set its name to ‘Jason
Bourne’ and make it return its name.

CODE Exercise

Remember, we had a cat?

So, how do you protect your cat from becoming flat?

(A) Create a class with the name “Cat”.

(B) Create a method to set the “height” of your cat.

(C) Create a method with the name “ruffOrDie” which can return “Meow…Meow” if
its height more than 9. If not than return “Biday Pitibi”.

(D) Now, create a new cat object with the name “myCat” and make it ruff or let it
die as flat!

You might also like