Wednesday, August 8, 2012

Inheritance Basics



Assume the existence of a BankAccount class.

Define a subclass, SavingsAccount that contains the following:
a double instance variable, interestRate
a constructor that accepts a parameter of type double which is used to initialize the instance variable


public class SavingsAccount extends BankAccount{
private double interestRate;
public SavingsAccount(double interestRate) {
this.interestRate = interestRate;
}
}


Assume the existence of a Phone class. Define a subclass, CameraPhone that contains two instance variables: an integer named, imageSize, representing the size in megapixels (for simplicity assume a pixel takes up one byte-- thus megapixels equals megabytes) of each picture (i.e., 2 means each image is composed of 2 megapixels), and an integer named memorySize, representing the number of gigabytes in the camera's memory (i.e., 4 means 4 Gigabyes of memory). There is a constructor that accepts two integer parameters corresponding to the above two instance variables and which are used to initialize the respective instance variables. There is also a method named numPictures that returns (as an integer) the number of pictures the camera's memory can hold. Don't forget that a gigabyte is 1,000 megabytes.


public class CameraPhone extends Phone { public CameraPhone(int imageSize, int memorySize) { this.imageSize = imageSize; this.memorySize = memorySize; } public int numPictures() {return memorySize * 1000 / imageSize;} private int imageSize; private int memorySize;}


Assume the availability of an existing class, ICalculator, that models an integer arithmetic calculator and contains:
an instance variable currentValue that stores the current int value of the calculator
methods add, sub, mul, and div

Each method in ICalculator receives an int argument and applies its operation to currentValue and returns the new value of currentValue. So, if currentValue has the value 8 and sub(6) is invoked then currentValue ends up with the value 2, and 2 is returned.

So, you are to write the definition of a subclass, ICalculator1, based on ICalculator. The class ICalculator1 has one additional method, sign, that receives no arguments, and doesn't modify currentValue. Instead, it simply returns 1, 0 or -1 depending on the whether currentValue is positive, zero, or negative respectively.


public class ICalculator1 extends ICalculator { public int sign() {return Integer.signum(getCurrentValue());}}



Assume you have a class Square. This class has an instance variable, side that is protected and of type double.

Write the class definition of a subclass of Square called FancySquare that has a method called getDiagonal. The getDiagonal method gets no arguments but returns the value of side multiplied by the square root of two.

class FancySquare extends Square {                double getDiagonal() {return side*Math.sqrt(2.0);}            }



The superclass Calculator contains:
a (protected) double instance variable, accumulator, that contains the current value of the calculator.
write a subclass, CalculatorWithMemory, that contains:
a double instance variable, memory, initialized to 0
a method, save, that assigns the value of accumulator to memory
a method, recall, that assigns the value of memory to accumulator
a method, clearMemory, that assigns zero to memory
a method, getMemory, that returns the value stored in memory


public class CalculatorWithMemory extends Calculator {
public void save() {memory = accumulator;}
public void recall() {accumulator = memory;}
public void clearMemory() {memory = 0;}
public double getMemory() {return memory;}
private double memory;
}



Given an existing class, BankAccount, containing:
a constructor accepting a String corresponding to the name of the account holder.
a method, getBalance, that returns a double corresponding to the account balance.
a method withdraw that accepts a double, and deducts the amount from the account balance.
Write a class definition for a subclass, CheckingAccount, that contains:
a boolean instance variable, overdraft. (Having overdraft for a checking account allows one to write checks larger than the current balance).
a constructor that accepts a String and a boolean. The String parameter is used in the invocation of the superclass (BankAccount) constructor, while the boolean is used to initialize the overdraft instance variable.
a method, hasOverdraft, that returns a boolean. hasOverdraft returns true if the account supports overdraft.
a method, clearCheck, that accepts a double and returns a boolean. clearCheck will determine if the amount (of the check) can be cashed-- this will be the case if the amount is less than the balance in the account, or if the account allows overdraft. If the check can be cashed, clearCheck returns true, and also calls the withdraw method to update the account balance; otherwise, clearCheck returns false.


class CheckingAccount extends BankAccount {                CheckingAccount(String name, boolean overdraft) {                    super(name);                    this.overdraft = overdraft;                }                boolean hasOverdraft() {return overdraft;}                boolean clearCheck(double amount) {                    if (getBalance() >= amount || overdraft) {                        withdraw(amount);                        return true;                    }                    return false;                }                boolean overdraft;            }



The superclass Student contains:
a constructor that accepts a String corresponding to the name of the school the student attends
a toString method that returns 'student at X' where X is the name of the school the student attends.

Write a class definition for the subclass HighSchoolStudent containing:
a constructor accepting a String which is used as a parameter to the superclass constructor
a toString method that returns 'high school student at X'. This method must use the toString method of its superclass.


class HighSchoolStudent extends Student {                HighSchoolStudent(String name) {super(name);}                public String toString() {return "high school " + super.toString();}            }



A Color class has three public accessor methods: getRed, getGreen, getBlue, that return that value (integer) of the corresponding color component for that color.
The class AlphaChannelColor-- a subclass of Color-- has a default constructor.
Declare a variable of type AlphaChannelColor and initialize it to an AlphaChannelColor object created using the default constructor. Send the values of the red, green, and blue components (in that order and separated by spaces) to System.out


AlphaChannelColor acc = new AlphaChannelColor();System.out.println(acc.getRed() + " " + acc.getGreen() + " " + acc.getBlue());



A Color class has three public, integer-returning accessor methods: getRed, getGreen, and getBlue, and three protected, void-returning mutator methods: setRed, setGreen, setBlue, each of which accepts an integer parameter and assigns it to the corresponding color component.
The class, AlphaChannelColor-- a subclass of Color-- has an integer instance variable, alpha, containing the alpha channel value, representing the degree of transparency of the color. AlphaChannelColor also has a method named dissolve (void-returning, and no parameters), that causes the color to fade a bit. It does this by incrementing (by 1) all three color components (using the above accessor and mutator methods) as well as the alpha component value.
Write the dissolve method.

public void dissolve() { setRed(getRed()+1); setGreen(getGreen()+1); setBlue(getBlue()+1); alpha++;}



Assume the availability of an existing class, ICalculator, that models an integer arithmetic calculator and contains:
an instance variable currentValue that stores the current int value of the calculator
a getter method for the above instance variable
methods add, sub, mul, and div

Each method in ICalculator receives an int argument and applies its operation to currentValue and returns the new value of currentValue. So, if currentValue has the value 8 and sub(6) is invoked then currentValue ends up with the value 2, and 2 is returned.

So, you are to write the definition of a subclass, ICalculator3, based on ICalculator. The class ICalculator3 overrides the div method of ICalculator. It checks its argument and if the argument is zero, it prints to standard output the message "ZERO DIVIDE ATTEMPT" and simply returns the value of currentValue. Otherwise, if the argument is NOT zero, the method invokes the base class method div (from ICalculator) and returns the value that it receives from that call.


public class ICalculator3 extends ICalculator {    public int div(int x) {        if (x!=0) return super.div(x);        System.out.println("ZERO DIVIDE ATTEMPTED");        return getCurrentValue();    }}


The superclass, EducationalInstitution, contains:
an int instance variable, duration, indicating the standard number of years spent at the institution
A constructor that accepts an int which is used to initialize the duration instance variable
a method graduationRequirements that returns a String. The (default) behavior of graduationRequirements is to return a String stating "d years of study", where d is the value of the duration instance variable
Write a class definition for the subclass LawSchool that contains:
a (default) constructor that invokes the superclass constructor with the value 3 (law school is typically a three year program).
a (overridden) method graduationRequirements that returns the string "3 years of study and passing the bar". You MUST invoke the graduationRequirements method of the superclass in this method (to obtain the first portion of the resulting string).


class LawSchool extends EducationalInstitution {                LawSchool() {super(3);}                String graduationRequirements() {return super.graduationRequirements() + " and passing the bar";}            }




A Color class has a method getColorName that returns a string corresponding to the common name for the color, e.g., yellow, blue, white, etc. If there is no common name associated with the color, null is returned.
The class, AlphaChannelColor-- a subclass of Color-- has an integer instance variable, alpha, containing the alpha channel value, representing the degree of transparency of the color.
Write the method getColorName of AlphaChannelColor, that overrides the method in the Color class. AlphaChannelColor's getColorName should return the name of the color (obtained from the getColorName method of Color) prefixed with the word 'opaque' if the alpha value is less than 100, 'semi-transparent' if the alpha value is otherwise less than 200, and 'transparent' otherwise (separate the prefix from the color name by a blank). If the color has no name, the method should return "opaque color", "semi-transparent color", or "transparent color", according the the same alpha values as above.



public String getColorName() { String name = super.getColorName(); if (name == null) name = "color"; if (alpha < 100) return "opaque " + name; else if (alpha < 200) return "semi-transparent " + name; return "transparent " + name;}



Assume the existence of a BankAccount class with a method, getAvailable that returns the amount of available funcs in the account (as an integer), and a subclass, OverdraftedAccount, with two integer instance variables: overdraftLimit that represents the amount of money the account holder can borrow from the account (i.e., the amount the account balance can go negative), and overdraftAmount, the amount of money already borrowed against the account. Override the getAvailable method in OverdraftedAccount to return the amount of funcds available (as returned by the getAvailable method of the BankAccount class) plus the overdraftLimit minus the overdraftAmount.

public int getAvailable() {return super.getAvailable() + (overdraftLimit - overdraftAmount);}


Many city ordinances have a requirement that buildings be surrounded by a certain amount of empty space for sunlight and fresh air. Apartment buildings-- begin residences and in particular multiple dwelling, usually have higher requirements than commercial or single residence properties. These requirements are often based upon square footage, number of occupants, etc. Assume the existence of a class Building with a method getRequiredEmptySpace that returns the amount of empty space (as an integer representing square feet) for the building. Asume further, a subclass, ApartmentBuilding, with two integer instance variables: totalUnits representing the number of apartments in the building and maxOccupantsPerunit, represents the maximum number of people allowed in each unit, by law. Override getRequiredEmptySpace in ApartmentBuilding to reflect the fact that apartment buildings require an addition square foot of empty space around it for each potential person living in the building.


public int getRequiredEmptySpace() { return super.getRequiredEmptySpace() + totalUnits * maxOccupantsPerUnit;}



Assume the existence of a Window class with a method getClientAreaHeight that returns an integer representing the height of the portion of the window that an application program can use for its display. Assume also, a subclass BorderedWindow with an integer instance variable borderSizeh, that represents the size of the border around the window. Override the getClientAreaHeight in BorderWindow to return the client area height as returned by the superclass minus the border size (taking into account top and bottom borders).


public int getClientAreaHeight() {return super.getClientAreaHeight() - 2 * borderSize;}


Assume the existence of a Phone class with a method, clear, that clears the phone's memory-- its phone book, list of call, text messages, etc. Assume also, a subclass CameraPhone with an instance variable, album, of type PhotoAlbum-- which has a method, also called clear that clears its contents. Override the clear method in CameraPhone to clear the entire phone, i.e., to invoke the clear method of Phone (the superclass), as well as invoking the clear method of the album instance variable.


public void clear() { super.clear(); album.clear();}


Assume the existence of a Building class with a constructor that accepts two parameters: a reference to an Address object representing the building's address, and an integer for the square footage of the building. Assume a subclass ApartmentBuilding has been defined with a single integer instance variable, totalUnits. Write a constructor for ApartmentBuilding that accepts three parameters: an Address and an integer to be passed up to the Building constructor, and an integer used to initialize the totalUnits instance variable.


ApartmentBuilding(Address address, int squareFootage, int totalUnits) { super(address, squareFootage);    this.totalUnits = totalUnits;}


Assume the existence of a BankAccount class with a constructor that accepts two parameters: a string for the account holder's name, followed by an integer for the account number. Assume a subclass SavingsAccount has been defined with a double instance variable named interestRate. Write a constructor for SavingsAccount that accepts three parameters (in the following order): a string and an integer that are passed to the constructor of BankAccount, and a double that is used to initialize the instance variable.

public SavingsAccount(String name, int socSecNum, double interestRate) { super(name, socSecNum); this.interestRate = interestRate;}


A Color class has a constructor that accepts three integer parameters: red, green and blue components in the range of 0 ... 255 with 0 representing no contribution of the component and 255 being the most intense value for that component.
The effect of full or semi-transparency can be achieved by adding another component to the color called an alpha channel. This value can also be defined to be in the range of 0...255 with 0 representing opaque or totally non-transparent, and 255 representing full transparency.
Define a class AlphaChannelColor to be a subclass of the Color class. AlphaChannelColor should have the following: - an integer instance variable alpha - a constructor that accepts four parameters: red, green, blue and alpha values in that order. The first three should be passed up to the Color class' constructor, and the alpha value should be used to initialize the alpha instance variable. - a getter (accessor) method for the alpha instance variable

public class AlphaChannelColor extends Color { public AlphaChannelColor(int red, int green, int blue, int alpha) { super(red, green, blue); this.alpha = alpha; }    public int getAlpha() {return alpha;} private int alpha;}


Assume the existence of a Window class with a constructor that accepts two integer parameters containing the width and height of the window (in that order).
Assume a subclass TitledWindow has been defined that has two instance variables:
a string named text for the text of the title and,
an integer, titleBarHeight for the height of the title bar. Write a constructor for TitledWindow that accepts four parameters:
two integers containing the width and height (which are passed up to the Window constructor), and,
a string and integer which are used to initialize the TitledWindow instance variables. The height of the title bar should be 'clamped' by the constructor to one half the height of the window-- i.e., if the height of the title bar passed into the constructor is greater than one half the specified height of the window, it should be set to one half the height of the window.


TitledWindow(int width, int height, String text, int titleBarHeight) { super(width, height); this.text = text; if (titleBarHeight > height / 2) titleBarHeight = height / 2; this.titleBarHeight = titleBarHeight;}



Assume the existence of a Phone class with a constructor that accepts two parameters: a string for the phone number followed by a boolean representing whether the phone provides added-value services. Assume a subclass MP3Phone has been defined that has two instance variables: an integer, memorySize, for the size, in megabytes of the phone memory, and a boolean, playsAAC, representing whether the phone is capable of playing AAC-encoded audio files. Write a constructor for MP3Phone that accepts three parameters: a String for the phone number (which is passed up to the Phone constructor, together with the value true for the added-value boolean), and an integer followed by a boolean for the instance variables.


MP3Phone(String phoneNumber, int memorySize, boolean playsAAC) { super(phoneNumber, true); this.memorySize = memorySize; this.playsAAC = playsAAC;}


A Color class has three integer color component instance variable: red, green, and blue.
Write a toString method for this class. It should return a string consisting of the three color components (in the order red, green, blue) within parentheses, separated by commas, with a '#' prefix e.g. #(125, 30, 210)

public String toString() {return "#(" + red + "," + green + "," + blue + ")";}



Write a class named Book containing:
Two instance variables named title and author of type String.
A constructor that accepts two String parameters. The value of the first is used to initialize the value of title and the value of the second is used to initialize author .
A method named toString that accepts no parameters. toString returns a String consisting of the value of title , followed by a newline character, followed by the value of author .


public class Book
{
private String title;
private String author;
public Book (String title, String author)
{
this.title = title;
this.author = author;
}
public String toString()
{
return title+ "\n" + author;
}
}



Write a class named Book containing:
Three instance variables named title, author, and tableOfContents of type String. The value of tableOfContents should be initialized to the empty string.
An instance variable named nextPage of type int, initialized to 1.
A constructor that accepts two String parameters. The value of the first is used to initialize the value of title and the value of the second is used to initialize author.
A method named addChapter that accepts two parameters. The first, of type String, is the title of the chapter; the second, is an integer containing the number of pages in the chapter. addChapter appends (that is concatenates) a newline followed by the chapter title followed by the string "..." followed by the value of the nextPage instance variable to the tableOfContents. The method also increases the value of nextPage by the number of pages in the chapter.
A method named getPages that accepts no parameters. getPages returns the number of pages in the book.
A method named getTableOfContents that accepts no parameters. getTableOfContents returns the values of the tableOfContents instance variable.
A method named toString that accepts no parameters. toString returns a String consisting of the value of title, followed by a newline character, followed by the value of author.

public class Book{
private String title;
private String author;
private String tableOfContents = "";
private int nextPage = 1;
public Book (String a , String b){
this.title = a;
this.author = b;
}
public void addChapter (String chapterTitle, int number){
tableOfContents += "\n" + chapterTitle + "..." + nextPage;
nextPage += number;
}
public int getPages(){
return nextPage-1;
}
public String getTableOfContents(){
return tableOfContents;
}
public String toString(){
return title + "\n" + author;
}
}





3 comments:

  1. Given an existing class, BankAccount, containing:
    a constructor accepting a String corresponding to the name of the account holder.
    a method, getBalance, that returns a double corresponding to the account balance.
    a method withdraw that accepts a double, and deducts the amount from the account balance.
    Write a class definition for a subclass, CheckingAccount, that contains:
    a boolean instance variable, overdraft. (Having overdraft for a checking account allows one to write checks larger than the current balance).
    a constructor that accepts a String and a boolean. The String parameter is used in the invocation of the superclass (BankAccount) constructor, while the boolean is used to initialize the overdraft instance variable.
    a method, hasOverdraft, that returns a boolean. hasOverdraft returns true if the account supports overdraft.
    a method, clearCheck, that accepts a double and returns a boolean. clearCheck will determine if the amount (of the check) can be cashed-- this will be the case if the amount is less than the balance in the account, or if the account allows overdraft. If the check can be cashed, clearCheck returns true, and also calls the withdraw method to update the account balance; otherwise, clearCheck returns false.

    Really need help with this one!!!

    ReplyDelete
  2. Can you help with this one:

    Assume the existence of a Building class. Define a subclass, ApartmentBuilding that contains the following instance variables: an integer, numFloors, an integer, unitsPerFloor, a boolean, hasElevator, a boolean, hasCentralAir, and a string, managingCompany containing the name of the real estate company managing the building. There is a constructor containing parameters for the initialization of the above variables (in the same order as they appear above). There are also two methods: the first, getTotalUnits, accepts no parameters and returns the total number of units in the building; the second, isLuxuryBuilding accepts no parameters and returns true if the building has central air, an elevator and 2 or less units per floor.

    ReplyDelete
    Replies
    1. the dude in your classDecember 12, 2012 at 8:34 PM

      public class ApartmentBuilding extends Building {
      private int numFloors, unitsPerFloor;
      private boolean hasElevator, hasCentralAir;
      private String managingCompany;

      public ApartmentBuilding(int numFloors, int unitsPerFloor, boolean hasElevator, boolean hasCentralAir, String managingCompany) {
      this.numFloors = numFloors;
      this.unitsPerFloor = unitsPerFloor;
      this.hasElevator = hasElevator;
      this.hasCentralAir = hasCentralAir;
      this.managingCompany = managingCompany;
      }

      public int getTotalUnits() {return unitsPerFloor * numFloors;}
      public boolean isLuxuryBuilding() {
      if (unitsPerFloor <= 2 && hasElevator && hasCentralAir) {
      return true;
      } else {
      return false;
      }
      }
      }

      Delete