Beruflich Dokumente
Kultur Dokumente
d. Hiding internal data from the outside world, and accessing it only through publicly exposed
methods is known as data .
Encapsulation
d) If a class contains only private data fields and no set methods, is the class mutable?
If not getter or setter method the value cant be accessed from outside the class.
Part 3
Design a class named Rectangle to represent a rectangle. The class contains:
Two double data fields named width and height that specify the width and height of the
rectangle. The default values are 1 for both width and height.
A string data field named color that specifies the color of a rectangle. Hypothetically,
assume that all rectangles have the same color. The default color is white.
A no-arg constructor that creates a default rectangle.
A constructor that creates a rectangle with the specified width and height.
The accessor and mutator methods for all three data fields.
A method named getArea() that returns the area of this rectangle.
A method named getPerimeter() that returns the perimeter
public Rectangle()
{
width = 1;
height = 1;
color = "white";
}
//Set Height
public void setHeight(double newHeight)
{
height = newHeight;
}
//Set Width
public void setWidth(double newWidth)
{
width = newWidth;
}
public void setColor(String c)
{
color = c;
}
//Find area
public double findArea()
{
return height*width;
}
// Find Parameter
public double findPerimter()
{
return (height*2) + (width*2);
}
}
Part 4
Design a class named Stock that contains:
A string data field named symbol for the stock's symbol. Done
A string data field named name for the stock's name. Done
A double data field named previousClosingPrice that stores the stock price for the
previous day. Done
A double data field named currentPrice that stores the stock price for the current time.
Done
A constructor that creates a stock with specified symbol and name.
The accessor methods for all data fields. Done
The mutator methods for previousClosingPrice and currentPrice.
A method named changePercent() that returns the percentage changed from
previousClosingPrice to currentPrice.
Symbol = s;
Name = n;
}
// Accessor/Getter Method for all the data fields.
public String getSymbol()
{
return symbol;
}
Public String getName()
{
Return name;
}
}
}
Part 5
b) Does every class have a toString method? How is it used? Is it appropriate to override
this method?
c) Suppose that Fruit, Apple, Orange, Golden Delicious Apple, and Macintosh Apple are
declared as on the diagram below. Assume that fruit is an instance of GoldenDelicious
and orange is an instance of Orange. Answer the following questions:
I. Is fruit instanceof Orange?
II. Is fruit instanceof Apple?
III. Is fruit instanceof GoldenDelicious?
IV. Is fruit instanceof Macintosh?
V. Is orange instanceof Orange?
VI. Is orange instanceof Fruit?