Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

For Circle Part 4, only use toString for spot2 (see below for an explanation of toString). Keep using the get and set methods for the

image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
image text in transcribed
For Circle Part 4, only use toString for spot2 (see below for an explanation of toString). Keep using the get and set methods for the other spot. The final output should look like this: Circle radius: 3.0 Circle circumference: 18.84 The formula for the area of a circle is a=Pi*r*r Circle area: 28.259999999999998 Circles are not equal. Circle has radius 4.0 toString() Method: Note that this method does not need to be called directly (For example, if there is a toString method in Circle you do not need to write println(spot2.toString()). You can simply write println(spot2) in the Test class. Since spot2 has been declared as a Circle object, Java automatically knows to use toString. client code TIP in fava, the controlling dass is the client code Client code refers to an application that uses one or more classes. The client can access the methods of the class, but cannot directly access the data defined in the class. This reinforces that the state of an object can only be changed through its behavior. TestCircle is client code. It uses the Circle class poble cum Turcle Curele spese Circle apott System.out.printrele de System.out.print in "Cicle era Rati: In the TestCircle application, a Circle object named is instantiated. The objects uses behavior setRadius to change the state of the object making the radius of the circle 5. Two other behaviors are implemented to produce the application output Circle radius: 5.0 Circle area: 78.5 Designing and Writing a Class Designing a class requires choosing the data the object will store and Functional determining the actions and communication the object will provide. The Decomposition design should include variable names and method names along with a The process of creating clearly description of the method and any required parameters. For example, the defined functions, or behavior Circle class design appears similar to for a class is sometimes called functional decomposition. A Circle well-written class has been functionally decomposed into variables: radius, PI a set of methods that cannot be simplified further methods setRadius - changes the radius. Requires one parameter for radius getRadius -returns the circle radius area - retums the area of the cirde based on the current radius A dass is written in a separate file and consists of a declaration and class declaration, body a body. The dass declaration includes the access level, the keyword clue and the class name. The dess body contains variables, constructors, and constructor methods. Constructors are used to initialize variables in a class Variables member and methods are called the members of a class A class takes the form: access_levels elect canales content bade Chapter 8 Classes and Object-Oriented Development J. ava applications use objects to perform tasks. Objects are defined with classes. This chapter explains how to design and write a class. The Object class and inheritance are introduced. Object-oriented development, encapsulation, and reusability are also discussed. What is an Object? In object-oriented programming, an object stores data and can perform state actions and provide communication. The state of an object refers to the behavior data it stores. The behavior of an object is defined by the action and com munication it provides Objects often model, or simulate, real-world things. For example, con- sider a circle shape. To create a Circle object modeled after the circle shape we analyze the state and behavior of the shape. A circle is defined by its radius, so this will make up the state of the object. A circle shape doesn't do much in the way of actions, but a Circle object could change its radius calculate its area, and tell us what its radius is. These actions will make up the behavior of a Circle object. TIP Adass is an abstract data An object is an instance of a class. A class is a data type that defines vari type, which was discussed in ables for the state of an object and methods for an object's behavior. Good Chapter 4. programming style dictates that the state of an object can only be changed through its behavior. For example, to change the radius of a Circle object a method for changing the radius variable must be called. Protecting an encapsulation object's data is called enampsulation. Encapsulation is also called information information hiding hiding because the object hides certain data from code outside the class For example, a Circle object declared in client code can be visualized as: Circle object declared in client code area and other methods in Circle class radius, Pl. and other data in Circle Class The Circle class code is based on the design on the previous page Organizing Files Cirele class Each class is written in a separate file. The client code and the classes it uses are then compiled together as part of a project public class Carele private state final double Pf. 3:14 patate double radius Constructor pre robe put A Carelesbject created. Radius initialized to 1 puble Circle 1/default radius Changes the res of the strele phone post: Radius but bees changed. publie vasi otadtwaldouble nevadelt tatus baie Interface The public methods of a class define the interface of an object. The interface is how client code can interact with an object. Calculate the area of the decin no peat the area of the code bas be returned puble double double crearea ettelezea - P1radlus.radius: returnerelereal SAN preho . Return the rade of the dele port: The radius of the circle has been returned puble double pet Radiu) tetutadual The Circle class has access level poble which means that it is visible to other classes and can be used to instantiate objects in those classes naming comentions The class name is Curele. A class name should be a noun, begin with an uppercase letter, and each word within the name should also begin with an uppercase letter Class names may not contain spaces The body of a class starts with an opening brace () and ends with a closing brace (). Member variables are declared after the opening brace, and outside of any methods. Variable declarations in the body of a class have a local scope that extends from the opening brace of the class body to the closing Note that the Circle class also has a member variable that is a constant Review: Circle - part 1 of 4 Modify the Circle class to include a member method named circumference. The circumference() method should return the circumference of the circle (21r). Test the class with the following client code: public static void main(String[] args) { Circle spot - new Circle(); spot.set Radius (3), System.out.println("Circle radius: + spot.getRadius()); System.out.println("Circle circumference: + spot.circumference()); Writing Constructors The constructor of a class is automatically executed when an object is instantiated. Once an object is instantiated, the method members of the class can be called in any order. Unexpected results may occur if an accessor method is called before a member variable has been set to a valid value. To prevent this variables should be initialized in the constructor A constructor takes the form: publte eius separantere>> overloading constructors The constructor of a class does not have a return type and always has the same name as the class. When a constructor contains parameters, they are separated by commas Constructors can be overloaded to provide more options for instantiat- ing an object. For example, if the radius of the circle object is known when the Circle object is created, it would be more efficient to assign the value to radius when the object is created Cirein spet sw Clocie 151 A constructor can be added to the Carcle class to handle creating an object with a parameter that contains the circle radius: /** Civele class publie cu Cele private statie a double P-3.14, pavate double caraar pre: pout A Cisele object create Radius initialized to 1 pellie Ciale //detalt radius SA conto poat: A Casele object created with ratua puble Circleldable at ...rest of Cinde diese When a class contains more than one constructor, the compiler uses the number and types of parameters to determine which constructor to execute. Review: Circle - part 2 of 4 Modify the Circle class to include an overloaded constructor that accepts the radius of the Circle object, as shown in the previous section Review: Rectangle - part 1 of 5 Design and then create a Rectangle class that has overloaded constructors. The first constructor requires no parameters. The second has two parameters, one for length and a second for width. Member variables store the length and width of the rectangle, and member methods assign and retrieve the length and width and return the area and perimeter of the rectangle. Test the class by writing appropriate client code. Instance and Class Members Each object, or instance of a class has its own copy of variables called instance variable instance Dariables. For example, the Circle class contains the instance class variable variable ratsun. A class may also contain class variables. A class variable is declared with the keyword ate and only one copy is maintained for all objects to refer to For example, the Circle class contains the class variable P1. Note that because Pl is a constant, it also includes the keyword final Circle cl puble clan Cirele private statie final do PI = 3,14 eina statant private double tadi i/iaatance variable ..rest of Circle class In the statements below, two Circle objects are instantiated. Each instance has its own copy of the instance variable ratus, but both objects refer to the same copy of the class constant ? Circle poti - Circle12 radius Curele pot2 Circa 19): rade Methods can be either instance methods or class methods Accessor instance methods and modifier methods are intstance methods because they change the state of an object. They must be called from an instance of a class Chapter 7 dass methods introduced dass methods that are declared with the keyword static. Class methods can be called from the class itself, rather than an object of the class, to perform a task. For example, consider the Circle class with the following class method added: . Duplays the formula for the sea of a circle pre: por The Formula for at dele bas been displayed public static void display Formula Systemut.printl. The formula for the area Circle 1: The following client code calls the displayArea Formula() class method: public class TestCircle public static void main(String argu) Circle spot new Circle(5) System.out.println("Circle radius:* + spot.getRadius()); System.out.println("Circle aren: apot, area); Circle.display#rea Formula); TIP Class methods cannot be used to change the value of an instance variable. The class method is called from the class itself (Circle) rather than an object of the class. The TestCircle application displays the following output: Circle radius: 5.0 Circle area: 78.5 The formula for the area of a circle is a:Pixar To summarize the differences between instance and class members: instance variables are created each time an object is declared. . class variables and constants are created once for the class and then objects of the class refer to this copy instance methods can only be called from an object of the class. class methods can be called from the class itself. inherit Subclasses inherit, or receive the methods of its superclass. The Object class includes methods for comparing objects and representing an object as a string Class Object (java.lang.Object) Method equals Object obj returns true if oby is equal to the object. toString returns a String that represents the object. TIP if a subclass does not over A subclass typically contains its own version of the equals() and toStringo ride the equals and toStringo superclass methods to better suit the object of the subclass. For example, methods, then the Object class two Circle objects are equal when they both have the same radius, and two methods are used. String objects are equal when they consist of the same set of characters. When a subclass redefines a superclass method, the subclass method override is said to override the superclass method. The Circle class should con- tain an equals() method that compares the state of the object to another Circle object and a toString() method that returns a String describing the object: equalso vs. == Objects compared using the operator are equal only if they refer to the same object The operator compares the references of the objects, not the data stored by the objects as the equals methods does. Determines if the object is equal to another Circle object precia Cirele object. poat: true has been returned 18 the objecte have the mendi tale has been returned otherwise */ public horloan equal Object el Circle testby - (Cirelele: if (testobootRadiun) -- adiun return true; Jelee return Ealsel SA Returns a Sering that represents the Circle object pret none poat: A string representing the Circle object has been returned publie String toString({ String cireleString: eireleSering - Civele ha radio radius retursleireleString: The equals() method requires an Object parameter. In the body of the object casting method, the obs parameter must be cast as the appropriate type, in this case Circle, and then assigned to an object of the appropriate type If an Object variable is cast with an incompatible class, then the exception ClassCastException ClassCastException will be generated. To convert an object to its superclass Object, no class casting is required. The code below creates two Circle objects, compares them, and displays information about the objects. An object's toString() method is invoked printino when an object is passed to the println() method: public static void main(String[] arga) Circle spotl = new Circle(3): Circle apot2 = new Circle(4): (spoti.equala (spot2)) { System.out.println("Objects are equal."); } else System.out.println("Objects are not equal."); TIP The concatenation opera- System.out.println(spot1); for also invokes the toStringo System.out.println(apot2): method of an object The code above displays the output: Objects are not equal. Circle has radius 3.0 Circle has radius 4.0 ) Review: Circle - part 4 of 4 Modify the Circle class to override the equals() and toString() methods, as shown in the previous section. Modify existing client code to test the new methods

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Transactions On Large Scale Data And Knowledge Centered Systems X Special Issue On Database And Expert Systems Applications Lncs 8220

Authors: Abdelkader Hameurlain ,Josef Kung ,Roland Wagner ,Stephen W. Liddle ,Klaus-Dieter Schewe ,Xiaofang Zhou

2013th Edition

ISBN: 3642412203, 978-3642412202

More Books

Students also viewed these Databases questions

Question

9.4 Tests of the Population Proportion (Large Samples)

Answered: 1 week ago

Question

x (b) Suppose f (x) = 9 find k such that lim f (x) =

Answered: 1 week ago