MyProgrammingLab - Chapter 10: Inheritance (Tony Gaddis)

Lakukan tugas rumah & ujian kamu dengan baik sekarang menggunakan Quizwiz!

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.

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

Assume the existence of a Window class with methods getWidth and getHeight, and a subclass TitledWindow, with a constructor accepts a string corresponding to the title of the window. Declare a variable, tWindow, of type TitledWindow variable, and initialize it to a TitledWindow object with a title of "My Title". Print out the width and height of the window (in that order) separated by a space.window (in that order) separated by a space.

TitledWindow tWindow = new TitledWindow("My Title"); System.out.print(tWindow.getWidth() + " " + tWindow.getHeight());

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.

public ApartmentBuilding(Address a, int b, int c) { super(a, b); totalUnits = c; }

The (abstract) class DesktopComponent contains an abstract method named onClicked that is void-returning and accepts no parameters. Provide the declaration of this method.

public abstract void onClicked();

Many systems provide the ability to have alternatives to visual or other sensory attributes (such as color or sound) for the purpose of accessibility (for example a picture to be displayed on a Web page may have a textual alternative that could be read by a text-to-speech peripheral for the usually impaired). Define an interface AccessibleGUIAttribute that contains a single method, getAlternativeText, that returns a string representing the textual alternative of an object. getAlternatrive accepts no parameters.210)

abstract interface AccessibleGUIAttribute { public abstract String getAlternativeText(); }

Regardles of its particular nature, all financial accounts provide a way to deposit and withdraw money. Define an interface Account that has two methods: deposit and withdraw, both of which accept a parameter of type Cash and return a boolean

abstract interface Account { public abstract boolean deposit(Cash a); public abstract boolean withdraw(Cash b); }

In order to respond to the click of a button, an object must be capable of being notified when the button was clicked. This is achieved by the Button object requiring that any such 'listener' provide a method named actionPerformed which can then be called to notify the listening object. Define an interface, ActionListener, with a single void-returning method, actionPerformed that accepts a single parameter of type ActionEvent.

abstract interface ActionListener { public abstract void actionPerformed(ActionEvent e); }

Regardless of the type of communications device, there must be a way to transmit and receive data. Define an interface, CommDevice, with two methods: transmit, that accepts two parameters -- reference to a Destination object, and a string (in that order), and returns a boolean; and receive, that accepts a parameter of type Duration, and returns a reference to a String.

abstract interface CommDevice { public abstract boolean transmit(Destination a, String b); public abstract String receive(Duration a); }

Windows on the desktop are just one of many objects used in a graphical user interface (GUI)-- buttons, drop-down list boxes, pop-up menus, are just some of the many others. Regardless of their particular appearance, tasks, and structure, all such GUI components share some common functionality-- which is handled in a manner unique to the actual component. Define an interface, GUIComponent, with the following methods: onClick-- void-returning and accepts a single integer parameter onCursorFocus -- void-returning and accepts a single integer parameter move -- 3 overloaded methods: all boolean-returning; one accepts a pair of integer parameters; the second a single parameter of type Position; the third a single parameter of type Dimension resize-- boolean-returning and accepts a pair of integer parameters

abstract interface GUIComponent { public abstract void onClick(int a); public abstract void onCursorFocus(int a); public abstract boolean move(int a, int b); public abstract boolean move(Position a); public abstract boolean move(Dimension a); public abstract boolean resize(int a, int b); }

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); } }

Assume the existence of a BankAccount class with a method, getAvailable that returns the amount of available funds 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 funds available (as returned by the getAvailable method of the BankAccount class) plus the overdraftLimit minus the overdraftAmount.

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

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 borderSize, 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).

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

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.

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

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 blah = new AlphaChannelColor(); System.out.println(blah.getRed() + " " + blah.getGreen() + " " + blah.getBlue());

Assume the existence of a Window class with the following methods: - widen - accepts no arguments; doubles the width of the window - setHeight - accepts an integer argument corresponding to the new height of the Window - getWidth and getHeight - accept no arguments, return the width and height of the window respectively. There is also a subclass, TitledWindow whose constructor accepts a width and height (bot integers), and a title (a string) -- in that order. TitledWindow also has a method, setText that accepts a string, allowing the title of the window to be changed. Declare a variable, tWindow, of type TitledWindow variable, and initialize it to a window with a width of 50 and a height of 75, and a title of "Rectangular Window". Double the width of the window, using widen, set the height of the window so that it is the same as the width, and set the title to the new value "Square Window".

TitledWindow tWindow = new TitledWindow(50, 75, "Rectangular Window"); tWindow.widen(); tWindow.setHeight(tWindow.getWidth()); tWindow.setText("Square Window");

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 a, int b, String c, int d) { super(a, b); text = c; titleBarHeight = d > a/2 ? a/2 : d; }

Define an interface GUIComponent consisting of four method declaration: open: void-returning, accepts no parameters close: both accepts no parameters, return boolean indicating whether or not the component is willing to be closed at that point (for example, a text window might have unsaved data and should not be closed) resize: void-returning accepts new width and height (integers) in that order move: void returning, accepts new x and y positions (in that order) respectively

abstract interface GUIComponent { public abstract void open(); public abstract boolean close(); public abstract void resize(int width, int height); public abstract void move(int x, int y); }

Write an interface, PointingDevice, containing: an abstract method, getXCoord that returns an int an abstract method, getYCoord that returns an int an abstract method, attentionRequired that returns a boolean an abstract method, setResolution that accepts a double and returns a double

abstract interface PointingDevice { public abstract int getXCoord(); public abstract int getYCoord(); public abstract boolean attentionRequired(); public abstract double setResolution(double a); }

Write an interface named 'Test' with the following behavior: a method 'getDuration' that returns a 'Duration' object. a method 'check' that accepts an integer parameter and returns a 'Result' object. a method 'getScore' that returns a double.

abstract interface Test { public abstract Duration getDuration(); public abstract Result check(int a); public abstract double getScore(); }

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.

public MP3Phone(String a, int b, boolean c) { super(a, true); memorySize = b; playsAAC = c; }

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 a, int b, double c) { super(a, b); interestRate = c; }

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() { return (alpha < 100 ? "opaque " : alpha < 200 ? "semi-transparent " : "transparent ") + (super.getColorName() != null ? super.getColorName() : "color"); }

Banks and other financial service companies offer many types of accounts for client's to invest their fund-- every one of them has a notion of their current value, but the details of calculating such value depends upon the exact nature of the account. Write an abstract class, Account, with the following: - an integer static variable, nextId initialized to 10001 - an integer instance variable, id - a string instance variable name - a constructor that accepts a single string parameter used to initialize the name instance variable. The constructor also assigns to id the value of nextId which is then incremented. - two accessor methods, getId and getName which return the values of the corresponding instance variables - an abstract method named getValue that accepts no parameters and returns and object of type Cash.

public abstract class Account { private static int nextId = 10001; private int id; private String name; public Account(String a) { name = a; id = nextId++; } public int getId() { return id; } public String getName() { return name; } public abstract Cash getValue(); }

Provide the definition of an abstract class named DesktopComponent that contains the following: - a void (abstract) method, onClicked, that accepts no parameters and is to be supplied by a subclass. - a (private) string named type, describing the sort of Desktop component (e.g. window, icon, taskbar, etc). - a constructor accepting a string that is used to initialize the type instance variable

public abstract class DesktopComponent { public abstract void onClicked(); private String type; public DesktopComponent(String a) { type = a; } }

All phones must have a way of making and then terminating a connection to the phone network; however the exact procedure for doing so depends upon the nature of the phone (e.g. landline, cell phone, satellite phone). Write a abstract class, Phone, that contains a string instance variable, phoneNumber, a constructor that accepts a string parameter initializing the instance variable, an accessor method, getPhoneNumber, that returns the phoneNumber, a toString method that return the phoneNumber in the form #(phoneNumber), and two abstract methods: a boolean-valued method named createConnection that returns a boolean and accepts an reference to an object of type Network, and a void-returning method, closeConnection, that accepts no parameters

public abstract class Phone { private String phoneNumber; public Phone(String a) {phoneNumber=a;} public String getPhoneNumber() {return phoneNumber;} public String toString() { return "#(" + phoneNumber + ")"; } public abstract boolean createConnection(Network a); public abstract void closeConnection(); }

Write a class definition for an abstract class, Vehicle, that contains: a double instance variable, maxSpeed a protected double instance variable, currentSpeed a constructor accepting a double used to initialize the maxSpeed instance variable an abstract method, accelerate, that accepts no parameters and returns nothing. a method getCurrentSpeed that returns the value of currentSpeed a method getMaxSpeed that returns the value of maxSpeed a method, pedalToTheMetal, that repeatedly calls accelerate until the speed of the vehicle is equal to maxSpeed. pedalToTheMetal returns nothing.

public abstract class Vehicle { private double maxSpeed; protected double currentSpeed; public Vehicle(double a) { maxSpeed = a; } public abstract void accelerate(); public double getCurrentSpeed() { return currentSpeed; } public double getMaxSpeed() { return maxSpeed; } public void pedalToTheMetal() { while(currentSpeed < maxSpeed) accelerate(); } }

All windows on the desktop have width and height (as well as numerous other attributes). However the actual contents of the window change both in structure and appearance depending upon what sort of window is displayed (e.g. a word processing window will display text, a color chooser window display a pallette of colors, a file chooser window displays a directory tree, etc). Thus, the details of the method to actual fill the contents of the window must be deferred to the subclasses of the Window class Write the definition of an abstract class, Window, containing the following: two integer instance variables, width and height, two accessor methods, getWidth and getHeight, a constructor that accepts two integers and uses them to initialize the two instance variables (the parameters should be width followed by height), and an abstract void-returning method named paint that accepts no parameters.

public abstract class Window { private int width, height; public Window(int a, int b) {width = a; height = b;} public int getWidth(){ return width; } public int getHeight(){ return height; } public abstract void paint(); }

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 { private int alpha; public AlphaChannelColor(int a, int b, int c, int d) { super(a,b,c); alpha = d; } public int getAlpha() { return alpha; } //public void setAlpha(int a) { alpha = a; } }

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.

public class ApartmentBuilding extends Building { private int numFloors; private int unitsPerFloor; private boolean hasElevator; private boolean hasCentralAir; private String managingCompany; public ApartmentBuilding(int a, int b, boolean c, boolean d, String e) { numFloors = a; unitsPerFloor = b; hasElevator = c; hasCentralAir = d; managingCompany = e; } public int getTotalUnits() { return unitsPerFloor * numFloors; } public boolean isLuxuryBuilding() { return hasElevator && hasCentralAir && (unitsPerFloor <= 2); } }

Given the abstract class, RentableDwelling, containing: a (private) double instance variable, rentPerUnit a constructor accepting a double used to initialize rentPerUnit a method, getRentPerUnit that returns the value of rentPerUnit an abstract method getRentalIncome that returns a double write a (non-abstract) subclass, ApartmentHouse, containing: an int instance variable numberOfApartments a constructor accepting a double, passed to the superclass constructor, and an int used to initialize numberOfApartments the method getRentalIncome calculated as the product of numberOfApartments and the rent per unit. getRentalIncome returns a double.

public class ApartmentHouse extends RentableDwelling { private int numberOfApartments; public ApartmentHouse(double a, int b) { super(a); numberOfApartments = b; } public double getRentalIncome() { return numberOfApartments * getRentPerUnit(); } }

Assume the existence of an interface, Account, with the following methods: - deposit: accepts an integer parameter and returns an integer - withdraw: accepts an integer parameter and return a boolean Define a class, BankAccount, that implements the above interface and has the following members: - an instance variable named balance - a constructor that accepts an integer that is used to initialize the instance variable - an implementation of the deposit method that adds its parameter to the balance variable. The new balance is returned as the value of the method. - an implementation of the withdraw method that checks whether its parameter is less than or equal to the balance and if so, decreases the balance by the value of the parameter and returns true; otherwise, it leaves the balance unchanged and returns false.

public class BankAccount implements Account { private int balance; public BankAccount(int a) { balance = a; } public int deposit(int a) { balance += a; return balance; } public boolean withdraw(int a) { if (a <= balance) { balance = balance - a; return true; } else { return false; } //balance -= a <= balance ? a : 0; return (a <= balance); } }

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 { private double memory = 0; public void save() { memory = accumulator; } public void recall() { accumulator = memory; } public void clearMemory() { memory = 0; } public double getMemory() { return memory; } }

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 { private int imageSize; private int memorySize; public CameraPhone(int a, int b) { imageSize = a; memorySize = b; } public int numPictures() { return memorySize * 1000 / imageSize; } }

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.

public class CheckingAccount extends BankAccount { private boolean overdraft; public CheckingAccount(String a, boolean b) { super(a); overdraft = b; } public boolean hasOverdraft() { return overdraft; } public boolean clearCheck(double a) { boolean clear = overdraft || a < getBalance(); if(clear) withdraw(a); return clear; } }

Assume the existence of an interface, CommDevice, with the following methods: transmit: accepts two string parameters and returns nothing receive: accepts two string parameters and returns a boolean Define a class, Firewall, that implements the above interface, and has the following members: a string instance variable, permittedReceiver a string instance variable, buffer a constructor that accepts a string parameter that is used to initialize the permittedReceiver variable an implementation of the transmit method that assigns the first parameter to the destination instance variable and the second to the buffer variable. It also send to System.out the message "Data scheduled for transmission to dest" where dest is replaced by the actual value of the destination string. an implementation of the receiver method that checks if the first parameter is equal to the permittedReceiver and if so it sets the buffer instance variable to the second parameter and returns true; otherwise it sets the buffer to the empty string, prints the message "Attempted breach of firewall by &lt;receiver&gt;" where &lt;receiver&gt; is replaced by the method's first parameter, and returns false.

public class Firewall implements CommDevice { private String permittedReceiver; private String buffer; public Firewall(String a) { permittedReceiver = a; } public void transmit(String a, String b) { buffer = b; System.out.print("Data scheduled for transmission to " + a); } public boolean receive(String a, String b) { if(a.equals(permittedReceiver)) { buffer = b; return true; } else { buffer = ""; System.out.print("Attempted breach of firewall by " + a); return false; } } }

Assume the existence of an interface, ActionListener, with the following method: - actionPerformed: void-returning, accepts no parameters Define a class, GUIApplication, that implements the above interface and has the following members: - an instance variable, doc, of type Document - a constructor that accepts a Document parameter used to initialize the instance variable - an implementation of the actionPerformed method that invokes the method, save, with the document instance variable as the receiver and sends the message "document saved" to System.out

public class GUIApplication implements ActionListener { private Document doc; public GUIApplication(Document a) { doc = a; } public void actionPerformed() { doc.save(); System.out.print("document saved"); } }

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.

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

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, 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() { if(super.getCurrentValue() == 0) return 0; else if (super.getCurrentValue() < 0) return -1; else return 1; //return Integer.compareTo(0); //return currentValue > 0 ? 1 : currentValue < 0 ? -1 : 0; } }

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 and can be accessed and modified by any subclass. 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, ICalculator2, based on ICalculator. The class ICalculator2 has one additional method, negate, that receives no arguments. The effect of negate is to reverse the sign of currentValue. For example, if currentValue is zero, there is no change, if it is -22 then it becomes 22, if it is 100 it becomes -100. Furthermore negate returns the new value of currentValue.

public class ICalculator2 extends ICalculator { public int negate() { return -(super.getCurrentValue()); } }

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 ATTEMPTED" 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 { @Override public int div(int a) { if(a == 0) { System.out.print("ZERO DIVIDE ATTEMPTED"); return super.getCurrentValue(); } else { return super.div(a); } } }

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).

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

Given the class 'ReadOnly' with the following behavior: A (protected) integer instance variable named 'val'. A constructor that accepts an integer and assigns the value of the parameter to the instance variable 'val'. A method name 'getVal' that returns the value of 'val'. Write a subclass named 'ReadWrite' with the following additional behavior: Any necessary constructors. a method named 'setVal' that accepts an integer parameter and assigns it the the 'val' instance variable. a method 'isDirty' that returns true if the setVal method was used to override the value of the 'val' variable.

public class ReadWrite extends ReadOnly { private boolean modified = false; public ReadWrite(int a) { super(a); } public void setVal(int a) { val = a; modified = true; } public boolean isDirty() { return modified; } }

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 a) { interestRate = a; } }

Assume the existence of an interface, GUIComponent with the following methods: - open and close: no parameters, returns boolean - move and resize: accepts two integer parameters and returns void Define a class, Window, that implements the GUIComponent interface, and has the following members: - width, height, xPos, and yPos integer instance variables, with xPos and yPos initialized to 0 - a constructor that accepts two integer variables (width followed by height) which are used ti initialize the width and height instance variables - An implementation of open: that sends "Window opened" to System.out, and returns true - An implementation of close that sends "Window closed" to System.out, and returns true - An implementation of resize that modifies the width and height variables to reflect the specified size - An implementation of move that modifies xPos and yPos to reflect the new position

public class Window implements GUIComponent { private int width, height, xPos = 0, yPos = 0; public Window(int a, int b) {width = a; height = b;} public boolean open() { System.out.print("Window opened"); return true; } public boolean close() { System.out.print("Window closed"); return true; } public void resize(int a, int b) { width = a; height = b; } public void move(int a, int b) { xPos = a; yPos = b; } }

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 = alpha+1; }


Set pelajaran terkait

COMM 313 Pearson 1 - 21 Quiz Answers & Study Guide

View Set

Cervical spine; Movements and Biomechanics

View Set

Sensory System Career Specialties

View Set

AP Euro - Chapter 21, the Industrial Revolution

View Set

Chapter 44- Genitourinary Dysfunction

View Set

chapter 10, chapter 11, chapter 15, chapter 16, International Marketing Chapter 17, intl marketing chapter 18, Int'l Ch. 16

View Set