Author Archives: graceliana@gmail.com

OOD Challenge Exercise

Chapter 1: VN 1.4 Solving a challenge exercise

Exercise 1:
Add a sunset to the single-sun version of Picture. That is: make the sun go
down slowly. Remember: The circle has a method slowMoveVertical
that you can use to do this.

Exercise 2: If you added your sunset to the end of the draw
method (so that the sun goes down automatically when the picture is
drawn), change this now. We now want the sunset in a separate method,
so that we can call draw and see the picture with the sun up, and then
call sunset (a separate method!) to make the sun go down.

You will find this code:
private Square wall;

private Square window;

private Triangle roof;

private Circle sun;

You need to add a line here for the second sun,

For example: private Circle sun2;

Then write the appropriate code for creating the second sun.

Exercise 3: Close the picture project, and open the lab-classes project.
This project is a simplified part of a student database designed to keep track of students in laboratory classes and to print class lists.
Create an object of class Student. You will notice that this time you
are not only prompted for a name of the instance, but also for some
other parameters. Fill them in before clicking Ok. (Remember that
parameters of type String must be written in double-quotes.)

OOD A Class Anatomy

OOD1
OOD2
OOD4
OOD5
OOD6
OOD7
OOD8
OOD9
OOD10
OOD11
OOD12

An ADT: Greeter

public class Greeter
{
   public String sayHello()
   {
      String message = "Hello, World!";
      return message;
   }
}

The tester class also called the driver:

public class GreeterTest
{
   public static void main(String[] args)
   {
      Greeter worldGreeter = new Greeter();
      System.out.println(worldGreeter.sayHello());
   }
}

An ADT: BankAccount

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      Constructs a bank account with a zero balance.
   */
   public BankAccount()
   {   
      balance = 0;
   }

   /**
      Constructs a bank account with a given balance.
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {   
      balance = initialBalance;
   }

   /**
      Deposits money into the bank account.
      @param amount the amount to deposit
   */
   public void deposit(double amount)
   {  
      balance = balance + amount;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      balance = balance - amount;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }
}

The driver class:

/**
   A class to test the BankAccount class.
*/
public class BankAccountTester
{
   /**
      Tests the methods of the BankAccount class.
      @param args not used
   */
   public static void main(String[] args)
   {
      BankAccount harrysChecking = new BankAccount();
      harrysChecking.deposit(2000);
      harrysChecking.withdraw(500);
      System.out.println(harrysChecking.getBalance());
      System.out.println("Expected: 1500");      
   }
}

Classwork:

  1. Add a method sayGoodbye to the Greeter class.
  2. Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”
  3. Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.
  4. Add a method
void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statemetns

BankAccount momsSavings = new BankAccount(1000);
momsSavings.addInterest(10); // 10% interest

the balance in momsSavings is $1,100.

Assignments:

  1. Add a method sayGoodbye to the Greeter class.
  2. Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”
  3. Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.
  4. Add a method
void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statemetns

BankAccount momsSavings = new BankAccount(1000);
momsSavings.addInterest(10); // 10% interest

the balance in momsSavings is $1,100.

OOD – Quick Intro Summary


Concepts and terms to know well

A class is like:

  • a category or type
  • a blue print
  • a factory
  • a template

A class defines how “objects” or “instances” should be created and maintained.

The “data fields” or “instance fields” define the state of the object.

The “methods” or “behaviors” manipulate the “data fields” or “instance fields” to ensure consistent and proper handling.

If you notice, the instance fields are private. This fact and the use of methods to handle the instance fields promotes ENCAPSULATION.

Unprotected data

Encapsulation

OOD: Car ADT

A class that defines an object with instance fields (attributes) and methods(behaviors) is called an ADT: Abstract Data Type

What is an abstraction?
Can you give an example of an abstraction?

“An abstraction is a general concept or idea, rather than something concrete or tangible. In computer science, abstraction has a similar definition. It is a simplified version of something technical, such as a function or an object in a program. The goal of “abstracting” data is to reduce complexity by removing unnecessary information.”
https://techterms.com/definition/abstraction

Implement a class Car_YI with the following properties.

  • A car has a certain fuel efficiency (measured in miles/gallon or liters/km—pick one) and a certain amount of fuel in the gas tank.
  • The efficiency is specified in the constructor, and the initial fuel level is 0.
  • Supply a method drive that simulates driving the car for a certain distance, reducing the fuel level in the gas tank, and methods getGas, returning the current fuel level, and addGas, to tank up.

Sample driver/test class:

Car_YI myBeemer = new Car_YI(29); // 29 miles per gallon 
myBeemer.addGas(20); // tank 20 gallons
myBeemer.drive(100); // drive 100 miles 
System.out.println(myBeemer.getGas()); // print fuel remaining


OOD – SavingsAccount

What to turn in when you submit your work in edmodo.com:
* a. Copy and paste both programs
* b. Attach both files
* c. Output should be included in your tester/driver class as a comment
* d. Test all your code: Think of data that will force execution of all the lines of code.

Classwork:
Write a class SavingsAccount_YI that is similar to the BankAccount class, except that it has an added instance variable interest. Supply a constructor that sets both the initial balance and the interest rate. Supply a method addInterest (with no explicit parameter) that adds interest to the account. Write a tester/driver program that constructs a savings account with an initial balance of $1,000 and interest rate 10%. Then apply the addInterest method five times and print the resulting balance.

bank

OOD: BankAccount

/**
   A bank account has a balance that can be changed by 
   deposits and withdrawals.
*/
public class BankAccount
{  
   private double balance;

   /**
      Constructs a bank account with a zero balance.
   */
   public BankAccount()
   {   
      balance = 0;
   }

   /**
      Constructs a bank account with a given balance.
      @param initialBalance the initial balance
   */
   public BankAccount(double initialBalance)
   {   
      balance = initialBalance;
   }

   /**
      Deposits money into the bank account.
      @param amount the amount to deposit
   */
   public void deposit(double amount)
   {  
      balance = balance + amount;
   }

   /**
      Withdraws money from the bank account.
      @param amount the amount to withdraw
   */
   public void withdraw(double amount)
   {   
      balance = balance - amount;
   }

   /**
      Gets the current balance of the bank account.
      @return the current balance
   */
   public double getBalance()
   {   
      return balance;
   }
}

/**
   A class to test the BankAccount class.
*/
public class BankAccountTester
{
   /**
      Tests the methods of the BankAccount class.
      @param args not used
   */
   public static void main(String[] args)
   {
      BankAccount harrysChecking = new BankAccount();
      harrysChecking.deposit(2000);
      harrysChecking.withdraw(500);
      System.out.println(harrysChecking.getBalance());
      System.out.println("Expected: 1500");      
   }
}

Classwork:

  1. Add a method sayGoodbye to the Greeter class.

  2. Add a method refuseHelp to the Greeter class. It should return a string such as “I am sorry, Dave. I am afraid I can’t do that.”

  3. Write a program that constructs a bank account, deposits $1000, withdraws $500, withdraws another $400, and then prints the remaining balance.

  4. Add a method

void addInterest(double rate)

to the BankAccount class that adds interest at the given rate. For example, after the statemetns

BankAccount momsSavings = new BankAccount(1000);
momsSavings.addInterest(10); // 10% interest

the balance in momsSavings is $1,100.

OOD – Encapsulation

Clearly explain the difference and similarities between these two lines of code:

harrysChecking.balance -= 500; // assume balance is not private (no encapsulation)

harrysChecking.withdraw(500); // encapsulation is enforced

Which one would you pick if you were Harry? Support your answer.

OOD: Pre conditions – Person

bug report
xkcd
Assignments:
1. Enhance the BetterBankAccount_YI class by adding preconditions
For the constructor: require the amount parameter to be at least zero
For the deposit method: require the amount parameter to be at least zero
For the withdraw method: the amount to be a value between 0 and the current balance

Driver: Write enough code in the tester class to invoke (call) all the methods.
Atm machines.

  1. Write a class Person with the following specifications:

a. Constructor: it takes a name as a string, a second string argument that describes what member of the family it is and, a third string describing the member activity to create a short story. You can make any changes you feel is necessary to accomplish this.

b. Mutator Method: setAge(int anAge). It prompts the user for age and updates the class instance field.

c. Mutator Method: setWhatIamDoing(String doing). It prompts the user and updates the class instance field currentActivity. Keep the number of activities low so it doesn’t become too lengthly.

d. Accessor Method: getWhatIamDoing(). It displays the currentActivity.

Tester class: MyFamilyDriver.java

despicableme2

Create or “instantiate” 4 persons, a mother, a father, a son or a daughter and a friend.
Simulate the following set of events:
The mother keeps milk in the refrigerator.
The father keeps juice in the refrigerator.
The son keeps a can of soda in the refrigerator.
The friend is thirsty and wants to drink something.

This is a story about “encapsulation” so your ending must reflect this concept. Be creative and use your imagination. The lines above is only an example. Do not use it for your own story. You can add more methods and instance fields to the Person ADT so you can make the simulation work nicely.

Some java language help:
String a = “abc”;
String b = “abcdefg”;
System.out.println(b.contains(a)); // true

OOD: Employee

employees

Implement a class Employee_YI. An employee has a name (a string) and a salary (a double). Write a default constructor, a constructor with two parameters (name and salary), and methods to return the name and salary. Write a tester/driver program that tests your class.
 

NOTE: Do not forget to document your work. Include header, a comment line for each method and constructor and input/output.