---
# System prepended metadata

title: Computer Programming II Lab 1
tags: [Computer Engineering, IUG, Lab, Computer Programming II]

---

---
title: Computer Programming II Lab 1
---
<h1 style='border: none'><center>Computer Programming II Lab 1</center></h1>
<h2 style='border: none'><center>Introduction to Object-Oriented Programming</br>Classes and Objects</center></h2>
<h5><center>The Islamic University of Gaza<br>Engineering Faculty<br>Department of Computer Engineering</center></h5>
<h6>Authors: Usama R. Al Zayan<span style="float:right">2023/02/08</span></h6>
<h6>Parts of this Lab were adapted from work done by Mohammed Nafiz ALMadhoun</h6>
---

## Objectives
* Be able to declare a new class.
* Be able to write a constructor.
* Be able to write instance methods that return a value.
* Be able to write instance methods that take arguments.
* Be able to instantiate an object.
* Be able to use calls to instance methods to access and change the state of an object.

## Lab 1: Time and Plan

| Tasks    | Timing   | 
| -------- | -------- |
| Task 1   | 20 min   |
| Task 2   | 10 min   |
| Task 3   | 10 min   |
| Task 4   | 10 min   |
| Task 5   | 20 min   |


## introduction

<p style="text-align:justify">
In this lab, we are going to talk about Object-Oriented programming and the idea of this concept, and how it helps us in making our codes more readable and scalable, the concept itself doesn’t change the way the programmes get executed, but it helps the developers in building much greater applications, and it makes it easier to reuse old codes, all the concepts in this course will not teach you any new logic thinking, it will teach you how to organize your code more.
</p>

<p style="text-align:justify">
Organizing the code is a very important step in writing it, after writing some codes if you didn’t organize it well, you won’t be able to modify or write more code in the same project, even if you see these concepts as extra steps you will do (and you can solve the problem in an old way easier), you should understand that without these concepts you won’t be able to write a medium-size program.
</p>

## What is a class

<p style="text-align:justify">
The class is one of the basic concepts in object-oriented world, the idea of class is a template for the data (and what we can do with it), so the class is the definition of the data that each object has, for example, an email has title, body, and from, you can create a class named Email that has a from as string, title as string, and body as string!
</p>

```java=
public class Email {
    String from;
    String title;
    String body;
}
```

For now, think about class as something to define your own custom data type.

## What is an Object

<p style="text-align:justify">
If you have a class you have a template for data, now the data itself is called an object, so if you have a specific email, you can create an object from the previous class and fill its data with the real data for that email.
</p>

<p style="text-align:justify">
Now you can create a method in that class to present or manipulate the data in that object, so for our previous class, we can create a method named printShort, this method will print the form field and title field in one row for that object.
</p>

## Class constructor

<p style="text-align:justify">
If you want to create an instance of the class (object), you may need to initialize the data in the object when you create it, so that is why there’s a constructor, the constructor is just a special method that got called when you create a new object of a specific class, the construct in Java should be named like the class name, and it doesn’t have any return type (as the construct should return the new object), a single class can have many constructors, these constructors should be different in the header.
</p>

```java=
class Email {
    String from;
    String subject;
    String body;
    public Email (String from, String subject, String body){
        this.from = from;
        this.subject = subject;
        this.body = body;
    }
}
```

So now we can create a new email object like this:

```java=
Email email = new Email ("email@iug.com", "This is a title", "This is the body");
```

<p style="text-align:justify">
Now you can create an array of emails if you want, and you could write another code to retrieve the emails from your email and fill that array.
</p>

<p style="text-align:justify">
What I need you to understand now, is that a class is a template for data, and the methods in that class are the thing that controls the data, now each instant of the class (object) is what contains the real data that got manipulated by the methods.
</p>

## Lab Tasks

<p style="text-align:justify">Everyone is familiar with a television. It is the object we are going to create in this lab.
First we need a blueprint. All manufacturers have the same basic elements in the televisions they produce as well as many options. We are going to work with a few basic elements that are common to all televisions. Think about a television in general. It has a brand name (i.e. it is made by a specific manufacturer). The television screen has a
specific size. It has some basic controls. There is a control to turn the power on and off. There is a control to change the channel. There is also a control for the volume. At any point in time, the television’s state can be described by how these controls are set.
</p>

<p style="text-align:justify">
We will write the television class. Each object that is created from the television class must be able to hold information about that instance of a television in fields. So a television object will have the following attributes:
</p>

* **`manufacturer:`** The manufacturer attribute will hold the brand name. This cannot change once the television is created, so will be a named constant.
* **`screenSize:`** The screenSize attribute will hold the size of the television screen. This cannot change once the television has been created so will be a named constant.
* **`powerOn:`** The powerOn attribute will hold the value true if the power is on, and false if the power is off.
* **`channel:`** The channel attribute will hold the value of the station that the television is showing.
* **`volume:`** The volume attribute will hold a number value representing the loudness (0 being no sound).

These attributes become fields in our class. The television object will also be able to control the state of its attributes. These controls become methods in our class.

* **`setChannel:`** The setChannel method will store the desired station in the channel field.
* **`power:`** The power method will toggle the power between on and off, changing the value stored in the powerOn field from true to false or from false to true.
* **`increaseVolume:`** The increaseVolume method will increase the value stored in the volume field by 1.
* **`decreaseVolume:`** The decreaseVolume method will decrease the value stored in the volume field by 1.
* **`getChannel:`** The getChannel method will return the value stored in the channel field.
* **`getVolume:`** The getVolume method will return the value stored in the volume field.
* **`getManufacturer:`** The getManufacturer method will return the constant value stored in the  `MANUFACTURER`  field.
* **`getScreenSize:`** The getScreenSize method will return the constant value stored in the  `SCREEN_SIZE`  field.

We will also need a constructor method that will be used to create an instance of a Television. 

These ideas can be brought together to form a UML (Unified Modeling Language) diagram for this class as shown below.

![](https://i.imgur.com/0hzKZWp.png)

### Task #1 Creating a new Class 

1. In a new file, create a class definition called  Television.
    * That is, the file should be named  `Television.java`
2. Put a program header (comments/documentation) at the top of the file 
    // The purpose of this class is to model a television 
3. Declare the 2 constant fields listed in the UML diagram.
4. Declare the 3 remaining fields listed in the UML diagram.
5. Write a comment for each field indicating what it represents.
6. Save this file as `Television.java`.
7. Compile and debug. Do not run.

### Task #2 Writing a Constructor 
1. Create a constructor definition that has two parameters, a manufacturer’s brand and a screen size. These parameters will bring in information
2. Inside the constructor, assign the values taken in from the parameters to the corresponding fields.
3. Initialize the powerOn field to false (power is off), the volume to 20, and the channel to 2.
4. Write comments describing the purpose of the constructor above the method header.
5. Compile and debug. Do not run.

### Task #3 Methods 
1. Define accessor methods called `getVolume`, `getChannel`, `getManufacturer`, and `getScreenSize` that return the value of the corresponding field.
2. Define a method called `setChannel` accepts a value to be stored in the channel field.
3. Define a method called `power` that changes the state from true to false or from false to true. This can be accomplished by using the `NOT` operator (`!`). If the boolean variable `powerOn` is `true`, then `!powerOn` is `false` and vice versa. 

* Use the assignment statement

```java
powerOn = !powerOn;
```
* to change the state of powerOn and then store it back into powerOn (remember assignment statements evaluate the right hand side first, then assign the result to the left hand side variable.
4. Define two methods to change the volume. One method should be called `increaseVolume` and will increase the volume by 1. The other method should be called `decreaseVolume` and will decrease the volume by 1.
5. Write javadoc comments above each method header.
6. Compile and debug. Do not run.

###  Task #4 Running the application
1. You can only execute (run) a program that has a main method, so there is a driver program that is already written to test out your Television class. Copy the file `TelevisionDemo.java`. Make sure it is in the same directory as Television.java
2. Compile and run TelevisionDemo.
3. If your output matches the output below, `Television.java` is complete and correct. You will not need to modify it further for this lab.

```shell=
A 55 inch Toshiba has been turned on.
What channel do you want? 56
Channel: 56 Volume: 21
Too loud!! I am lowering the volume.
Channel: 56 Volume: 15
```

### Task #5 Creating another instance of a Television

1. Edit the `TelevisionDemo.java` file.
2. Declare another Television object called portable.
3. Instantiate portable to be a Sharp 19 inch television.
4. Use a call to the power method to turn the power on.
5. Use calls to the methods to print what television was turned on.
6. Use calls to the methods to change the channel to the user’s preference and decrease the volume by two.
7. Use calls to the methods to print the changed state of the portable.
8. Compile and debug this class.
9. Run `TelevisionDemo` again.
10. The output for task #5 will appear after the output from above, since we added onto the bottom of the program. The output for task #5 is shown below.

```shell=
A 19 inch Sharp has been turned on.
What channel do you want? 7
Channel: 7 Volume: 18
```

## TelevisionDemo.java
```java=
import java.util.Scanner;
/** This class demonstrates the Television class*/
public class TelevisionDemo{
   public static void main(String[] args){
      //create a Scanner object to read from the keyboard
      Scanner keyboard = new Scanner (System.in);
      //declare variables
      int station;   //the user's channel choice
      //declare and instantiate a television object
      Television bigScreen = new Television("Toshiba", 55);
      //turn the power on
      bigScreen.power();
      //display the state of the television
      System.out.println("A " + bigScreen.getScreenSize() + " inch " +
         bigScreen.getManufacturer()   + " has been turned on.");
      //prompt the user for input and store into station
      System.out.print("What channel do you want?  ");
      station = keyboard.nextInt();
      //change the channel on the television
      bigScreen.setChannel(station);
      //increase the volume of the television
      bigScreen.increaseVolume();
      //display the the current channel and volume of the television
      System.out.println("Channel:  " + bigScreen.getChannel() +
         "   Volume:  " + bigScreen.getVolume());
      System.out.println("Too loud!! I am lowering the volume.");
      //decrease the volume of the television
      bigScreen.decreaseVolume();
      bigScreen.decreaseVolume();
      bigScreen.decreaseVolume();
      bigScreen.decreaseVolume();
      bigScreen.decreaseVolume();
      bigScreen.decreaseVolume();
      //display the current channel and volume of the television
      System.out.println("Channel:  " + bigScreen.getChannel() +
         "   Volume:  " + bigScreen.getVolume());
      System.out.println();      //for a blank line
      //HERE IS WHERE YOU DO TASK #5
   }
}
```
###### tags: `Computer Programming II` `Lab` `IUG` `Computer Engineering`
<center>End Of Lab 1</center>