Download presentation
Presentation is loading. Please wait.
Published byBent Stene Modified over 5 years ago
1
LESSON 3 Reviewing Java Implementation Of OO Principles – Part 1
Classes, Encapsulation, Aggregation, Inheritance A Rapid Review CSC 300 Fall 2019 Howard Rosenthal
2
Course References Materials for this course have utilized materials in the following documents. Additional materials taken from web sites will be referenced when utilized. Anderson, Julie and Franceschi, Herve, Java Illuminated 5TH Edition,, Jones and Bartlett, 2019 Bravaco, Ralph and Simonson, Shai, Java Programming From The Ground Up, McGraw Hill, 2010 Deitel, Paul and Deitel, Harvey, Java, How To Program, Early Objects, Eleventh Edition, Pearson Publishing, 2018 Gaddis, Tony, Starting Out With Objects From Control Structures Through Objects, Seventh Edition, Pearson Publishing, 2019 Horstmann, Cay, Core Java For The Impatient, Addison Wesley- Pearson Education, 2015 Naftalin, Maurice and Wadler, Philip, Java Generics and Collections, O’Reilly Media, 2007 Schmuller, Joseph, Teach Yourself UML In 24 Hours Second Edition, SAMS Publishing, 2002 Urma, Raoul-Gabriel, Fusco, Mario and Mycroft, Alan, Java 8 in Action: Lambdas, Streams, and Functional-Style Programming, Manning Publishing, 2014 Wirfs-Brock, Rebecca, Wilkerson, Brian and Wiener, Laura, Designing Object-Oriented Software, Prentice Hall, 1990 Oracle On-Line Documentation and Tutorials,
3
Lesson Goals Review (from CSC 123) of how basic object-oriented principles are implanted in Java Classes and encapsulation Aggregation Inheritance
4
Object-Oriented Software Development In Java (Part 1)
5
What Is Object Oriented Programming
Object-Oriented programming consists of three stages: Creating the Program The programmer creates source files that define classes for objects the program will use when it is running. The programmer defines a class that contains the static main() method which is used to start the program running. Compiling the Program The program is compiled into bytecode. There may be several source files. Each is compiled into bytecode. Running the Program The java interpreter looks for a static main() method and starts running it. Since main() is static it can start running even though no objects have been created, yet. As the program runs, objects are created and their methods are activated. The program does its work by creating objects and activating their methods. The exact order of object creation and method activation depends on the task to be performed and the input data.
6
Objects In Java (1) An object exists in memory, and performs a specific task. Objects have two general capabilities under encapsulation: Objects can store data. The pieces of data stored in an object are known as fields. Objects can perform operations. The operations that an object can perform are known as methods. When a program needs the services of a particular type of object, it creates that object in memory using the keyword new, and then calls that object's methods as necessary. The class is the blueprint for objects of that type A class is code that describes a particular type of object. It specifies the data that an object can hold (the object's fields), and the actions that an object can perform (the object's methods).
7
Communicating Objects (1)
A running program is a collection of objects that are each doing their own task and communicating with other objects. The picture (next slide) shows a running program for a pizza shop. The jagged lines represent communication. The boss is special and so is drawn with dotted lines. In Java programs the main() method is special because it is where the Java interpreter starts the whole program running. The main() method is a static method, which means that there will be only one instance of it and that it exists (as part of a class) before any objects have been created. The class with the main method is usually referred to as the Driver Class or the Client.
8
Communicating Objects (2)
9
Classes and Encapsulation
10
Encapsulation And UML For An Auto
model: String milesDriven: int gallonsOf Gas: double + Auto(): + Auto(startModel: String, startMilesDriven: int, startGallonsOfGas: double): + getModel() : String + getMilesDrivenl() : int + getGallonsOfGas() : double + setModel(model: String) : void + setMilesDrivenl(milesDriven: int) : void + setGallonsOfGas(gallonsOfGas: double) : void + milesPerGallon() : double + toString() : String + equals(obj: Object) : boolean Notes: + means public means private # means protected ~ is for an internal variable Methods without return variables are constructors (some diagrams don’t use this convention) – constructor(s) still identified by the class name If the title or method is italicized it is an abstract class or method
11
The Syntax Of A Class Definition
Modifiers class ClassName { // Description of the instance variables // Description of the constructors // Description of the methods } A few notes: For now, replace modifiers with public in the class that contains main and don't include it in other classes in the same file. Separating the class into sections is done for clarity. It is not a rule of the language. A simple class might have just a few variables and be defined in just a few lines of code. A large, complicated class might take thousands of lines of code for its definition. Use a noun for the class name. Begin the class name with a capital letter
12
The Driver Class The Java interpreter starts a program by looking for a static main() method. Since the method is static the interpreter can run it without first constructing an object. It is convenient to have a separate class that serves no other purpose than to contain the main() method. This testing class is used to start things running. Sometimes the class that contains main() is called a driver Usually main() constructs objects of various classes and calls their methods. These objects do the real work of the program. When you compile the file, the compiler outputs two separate files of bytecodes, one for each class (see directory for class files)
13
Basic Terminology Fields Members Access Modifier
Instance variables: the data for each object Class data: static data that all objects share Members Fields and methods Access Modifier Determines access rights for the class and its members Defines where the class and its members can be used
14
public vs. private Classes are usually declared to be public
We need to be able to access them from other classes or they are useless Instance variables are usually declared to be private. It is good practice to make most instance variables private and only access them through meth0ds of the class We minimize the number of instance values and use methods to obtain derived values Methods that will be called by the client of the class are usually declared to be public. Methods that will be called only by other methods of the class are usually declared to be private. APIs (name and parameters of methods as well as return values) of methods are published (made known) so that clients will know how to instantiate objects and call the methods of the class. The third access modifier is protected, which we use less often
15
Instance Variables Each instance of a class has its own set of fields, which are known as instance fields. You can create several instances of a class and store different values in each instance’s fields. The methods that operate on an instance of a class are known as instance methods.
16
The Syntax Of An Instance Variable
accessModifier dataType identifierList; dataType can be a primitive data type or a class type. identifierList can contain: One or more variable names of the same data type Multiple variable names separated by commas Initialization values Optionally, instance variables can be declared as final. By convention capitalize any final variables. Conventions Begin the instance variable identifier with a lowercase letter and capitalize internal words as per our normal practices Define instance variables as private so that only the methods of the class will be able to set or change their values.
17
Methods In Classes When you write methods for any class follow all the same rules that are normally the case, including those related to overloading. If the method is going to be accessed from another class don’t use the word static Special rules relating using static Static methods are convenient for many tasks because they can be called directly from the class, as needed. A static method is created by placing the key word static after the access specifier in the method header. When a class contains a static method, it isn’t necessary for an instance of the class to be created in order to execute the method. The only limitation that static methods have is that they cannot refer to non-static members of the class. This means that any method called from a static method must also be static. It also means that if the method uses any of the class’s fields, they must be static as well.
18
Constructors Constructors are special methods that are called automatically when an object is instantiated using the new keyword Constructors do not have any return value in the header (nor in the body) A constructor is automatically executed each time an object of the class is instantiated. A constructor method has the same name as the class with appendage .java. The only exception to this is when you place multiple classes into the class containing main, in which case the file has the same name as the class containing main. A class can have several constructors. Each constructor must have a different number of parameters or parameters of different types – just like an overloaded method. The job of the class constructors is to initialize the instance variables of the new object. If and only if no constructor is specified a default constructor is used. The default constructor for a published class should be published as part of the class API
19
Syntax Of The Constructor
public ClassName( parameter list ) { // constructor body } See AutoClientV1.java, AutoV1.java
20
Default Instance Values
If the constructor does not assign values to the instance variables, they receive default values depending on the instance variable’s data type. (just like arrays) The default constructor doesn’t accept arguments. The only time that Java provides a default constructor is when you do not write your own constructor for a class.
21
A Note About Scope Instance variables have class scope
A constructor or method of a class can directly refer to instance variables. We will review the use of the keyword this in a few slides Methods also have class scope A constructor or method of a class can call other methods of a class (without using an object reference). This is just what we have done up to now with methods A method's parameters have local scope A method can directly access its parameters, - but one method's parameters cannot be accessed by other methods. A method can define variables which also have local scope A method can access its local variables, - but one method's local variables cannot be accessed by other methods.
22
Accessor Methods Clients cannot directly access private instance variables, so classes provide public accessor methods with this standard form: public returnType getInstanceVariable( ) { return instanceVariable; } Where (returnType is the same data type as the instance variable.) A simple example looks like this public int getCounter( ) return counter; See AutoClientV2.java, AutoV2.java
23
Mutator Methods Mutator methods allow the client to change the values of instance variables. They have this general form: public void setInstanceVariable( dataType newValue ) { // if newValue is valid, // assign newValue to the instance variable } A simple example: public void setMilesDriven( int newMilesDriven ) if ( newMilesDriven >= 0 ) milesDriven = newMilesDriven; else System.out.printf( "Miles driven "cannot be negative.\n" ); System.out.printf( "Value not changed.\n" ); See AutoClientV3.java, AutoV3.java and AutoClientV4.java, AutoV4.java (adding some useful methods)
24
The Object Reference this
How does a method know which object's data to use? The reference this refers to the current instance of a class, the object currently being used. this is an implicit parameter sent to methods. this is an object reference to the object for which the method was called. When a method refers to an instance variable name within an object, this is implied, unless the same variable name is used within the method. Thus, variableName is understood to be this.variableName this can be used in any method of the class, including any constructor. Example: public void setInstanceVariable(dataType instanceVariableName ) { this.instanceVariableName = instanceVariableName; } In the case above the true instance variable gets the value of the parameter
25
Using this (1) See AutoClientV5.java, AutoV5.java
public void setInstanceVariable(dataType instanceVariableName ) { this.instanceVariableName = instanceVariableName; } Or in a constructor public newObject (dataType1 IVN1, dataType2 IVN2) this.IVN1 = IVN1; this.IVN2 = IVN2; See AutoClientV5.java, AutoV5.java
26
Using this (2) Some programmers like to use this pattern:
public ClassName setInstanceVariable( dataType instanceVariableName ) { this.instanceVariableName = instanceVariableName; return this; } Example: public Auto setModel( String model ) this.model = model; See AutoClientV5.java, AutoV5.java
27
Calling A Constructor From A Constructor (1)
If one constructor calls another constructor, no other statements can precede that call. So look at the following class: public class Room { private int length; private int width; private int height; private double gallonsOfPaint; public Room() { length = 9; width =12; height = 8; } public Room(int length,int width, int height) // three-argument constructor this.length = length; this.width = width; this.height = height; } You can write it alternatively as shown on the next slide
28
Calling A Constructor From A Constructor (2)
So look at the following rewritten class: public class Room { private int length; private int width; private int height; private double gallonsOfPaint; public Room() { this(9, 12, 8);//does the same thing } public Room(int length,int width, int height) // three-argument constructor this.length = length; this.width = width; this.height = height; }
29
toString (1) The toString() method returns a String representing the data of an object Clients can call toString() explicitly by coding the method call. Clients can call toString() implicitly by using an object reference where a String is expected. Example client code: Auto compact = new Auto( ); // instantiate an object // explicit toString call System.out.printf( ”%s\n”, compact.toString( ) ); // implicit toString call System.out.printf(”%s\n”, compact ); Both printf statements produce the same output
30
toString (2) See AutoClientV6.java, AutoV6.java
Most classes can benefit from having a method named toString, which is implicitly called under certain circumstances. Typically, the method returns a string that represents the state of an object. Every class has a default toString() if one isn’t provided In general the default it is not all that useful, so we write what is called an overriding method When we look at inheritance we will be understand what is inherited and what is new in toString() See AutoClientV6.java, AutoV6.java
31
Using equals() In Classes
The purpose of equals() is to determine if the data in another object is equal to the data in this object. You cannot determine whether two objects contain the same data by comparing them with the == operator. Instead, the class must have a method such as equals for comparing the contents of objects. Like toString(), equals(Object obj) is inherited by every object. However, you almost always want to write an overriding method for your class, based on your definition of equality Note: later we will discuss the Comparator interface See AutoClientV6.java, AutoV6.java
32
instanceof Is A Special Binary Operator
We can use the instanceof operator to determine if an object reference refers to an object of a particular class. instanceof is not really a method, rather it is a special binary operator Syntax: objectReference instanceof ClassName evaluates to true if objectReference is of ClassName type; false otherwise. if ( ! ( obj instanceof AutoV6 ) ) return false; else o See AutoClientV6.java, AutoV6.java
33
What Does Overriding Mean
In any object-oriented programming language, overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. Some programmers use annotation, but it is not required
34
Rules For Overriding In Java
The argument list should be exactly the same as that of the overridden method. The return type should be the same or a subtype of the return type declared in the original overridden method in the superclass. The access level cannot be more restrictive than the overridden method's access level. For example: If the superclass method is declared public then the overriding method in the sub class cannot be either private or protected. Instance() methods can be overridden only if they are inherited by the subclass. A method declared final cannot be overridden. A method declared static cannot be overridden but can be re-declared. If a method cannot be inherited, then it cannot be overridden. A subclass within the same package as the instance's superclass can override any superclass method that is not declared private or final. A subclass in a different package can only override the non-final methods declared public or protected. An overriding method can throw any uncheck exceptions, regardless of whether the overridden method throws exceptions or not. However, the overriding method should not throw checked exceptions that are new or broader than the ones declared by the overridden method. The overriding method can throw narrower or fewer exceptions than the overridden method. Constructors cannot be overridden.
35
static Variables static variables are also known as class variables.
A static variable belongs to the class and not to any particular object; a class or static variable is shared by all objects of the class. One copy of a static variable is created per class. static variables are not associated with an object. static constants are often declared as public. When they are they are accessed as classname.variablename i.e. Math.PI To define a static variable, include the keyword static in its definition: Syntax: accessSpecifier static dataType variableName…; Example: private static int countAutos = 0;
36
Some Uses of static Variables
If the class is Employee, keep track of the total number of employees and total payroll with static variables If the class is Car, use a static variable to keep track of the total number of cars sold Keep track of the total number of letters going though a post office with a static variable
37
static Methods static methods are also called class methods
Often defined to access and change static variables static methods cannot access instance variables: static methods are associated with the class, not with any object. static methods do not have access to the implicit parameter this – remember this is a reference to the object. static methods cannot access non-static methods static methods can access static (class) variables To be accessed outside the class the method must be public You access a class method as follows classname.method(parameter list) classname is not needed within the class, only for external access Example: Math.sqrt(value) See AutoClientV7.java, AutoV7.java
38
Access Restrictions For static And Non-static Methods
Exception: A static method may be called whether or not an object of the class exists, but a static method cannot invoke an instance method except via an object. For example, main is static, but it can invoke non-static method of a class via the object reference.
39
Some Notes On Garbage Collection (1)
The Problem If unreferenced objects accumulate, a gargantuan program with thousands of objects could run out of memory. Even if a program does not run out of memory, if too much memory is allocated, program performance can deteriorate. We have seen how immutable objects, such as String objects, can quickly create large numbers of unreferenced objects. Fortunately, Java manages memory automatically, and this helps alleviate any potential disaster. The Java Virtual Machine automatically reclaims all memory allocated to unreferenced objects for future use. In other words, if an object is no longer referenced and accessible, the memory allocated to that object is freed and made available for the creation of other objects. This clean-up process is called garbage collection.
40
Some Notes On Garbage Collection (2)
Sometimes we create an object for short term use A memory leak occurs when an application maintains references to obsolete objects To avoid a memory leak, set any reference to an object equal to null when that object is no longer going to be used. A reference with value null refers to no object and holds no address; it is called a void reference. Once the object has no reference to it the JVM automatically frees up the space Remember: Managing memory use is an important part of a programmer’s job. The programmer must work in tandem with Java’s automatic garbage collection as described above to ensure that there are no memory leaks.
41
Aggregation
42
Aggregation Allows Us To Build Realistic Models
Aggregation occurs when an instance of a class is a field in another class In real life, objects are frequently made of other objects. A house, for example, is made of door objects, window objects, wall objects, and much more. It is the combination of all these objects that makes a house object. We have already done a bit of this with the use of String objects as instance variables. When designing software, it sometimes makes sense to create an object from other objects. For example, suppose you need an object to represent a course that you are taking in college. You decide to create a Course class, which will hold the following information: Course name Instructor Textbook The last two of these items are classes in there own right You could put fields for each of these items in the Course class. However, a good design principle is to separate related items into their own classes. In this example, an Instructor class could be created to hold the instructor-related data and a TextBook class could be created to hold the textbook-related data. Instances of these classes could then be used as fields in the Course class
43
A UML Envisioning Of A Course
44
Discussion On UML For the Instructor class
Three instance variables - the instructor’s last name, first name and office number A constructor which accepts arguments for the instructor’s last name, first name and office number A copy constructor A set method, which can be used to set all of the class’s fields A toString method See Instructor.java code
45
Discussion On UML For the Textbook class
Three instance variables - the title, author and publisher A constructor which accepts arguments for the title, author and publisher A copy constructor A set method, which can be used to set all of the class’s fields A toString method See TextBook.java code
46
Aggregation Example – The Course class
The Course class has an Instructor object and a TextBook object as fields, as well as a course name Making an instance of one class a field in another class is called object aggregation. The word aggregate means “a whole which is made of constituent parts.” In this example, the Course class is an aggregate class because it is made of constituent objects. When an instance of one class is a member of another class, it is said that there is a “has a” relationship between the classes. For example, the relationships that exist among the Course, Instructor, and TextBook classes can be described as follows: The course has an instructor. The course has a textbook The “has a” relationship is sometimes called a whole-part relationship because one object is part of a greater whole.
47
Discussion On UML For the Course class
Three instance variables - the courseName, Instructor and TextBook A constructor which accepts arguments for the the courseName, Instructor and TextBook A getName method to get the name of the course A getInstructor method to get a reference to a instructor object A getTextbook method to get a reference of the textBooks ListArray A toString method See Course.java code Then see CourseDemo.java
48
Security Issues With Aggregate Classes
Perform Deep Copies When you make a copy of an Aggregate object, you need to make copies of any object within the aggregate. Don’t just reference the same objects – don’t make a shallow copy Shallow copies can create security holes. For instance, if you copy a course with a shallow copy you my have both courses referring to the same list of books However, you need to separate these so that you can change the name of the books in one of the courses without changing the books in the second course Of course you don’t need to worry about immutable objects, since they can’t be changed When an object is requested, create a new Object that is a copy of the original, and return a reference to it. This keeps the user from getting access to the original object.
49
Inheritance
50
Basic Principles Of Inheritance
A common form of reuse of classes is inheritance. We can organize classes into hierarchies of functionality. The class at the top of the hierarchy (superclass) defines instance variables and methods common to all classes in the hierarchy. We derive a subclass, which can inherit both behavior and fields from the superclass.
51
Specifying Inheritance In Java
The syntax for defining a subclass is to use the extends keyword in the class header, as in accessModifier class SubclassName extends SuperclassName { // class definition – new variables, constructors and other methods (new or overriding) } The superclass name specified after the extends keyword is called the direct superclass. As mentioned, a subclass can have many superclasses, but only one direct superclass.
52
UML For The Video and Movie3 classes
Let’s look at the following files: TestVideoStore.java, Video.java, Movie3.java The Movie is a subclass of Video Video -title:String -length:int -avail:boolean +Video(ttl:String, lngth:int) +toString():String +getTitle():String +setTitle(ttl:String):void +getLength():int +setLength(lng:int):void +getAvailable():boolean +setAvailable(avl:boolean):void Movie3 -director:String -rating:String +Movie3(ttl:String, lngth:int, dir:String, rtng:String)) +getDirector():String +getRating():String +toString():String
53
A Simple Example With Inheritance
Let’s look at the following files: TestVideoStore.java, Video.java, Movie3.java The class Movie is a subclass of Video. An object of type Movie has these members: member title accessible from Video getTitle() inherited from Video setTitle() length getLength() setLength() avail getAvailable() setAvailable() director defined in Movie3 getDirector() defined in Movie3 toString() overriden in Movie3 rating getRating() defined in Video
54
Using A Super Constructor (1)
Look at he constructor for class Movie. The class definition for Video has a constructor that initializes the instance variables of Video objects. The class Movie has a constructor that initializes the instance variables of Movie objects. The statement super(ttl, lngth) invokes a constructor of the parent to initialize some variables of the child. There are two constructors in the parent. The one that is invoked is the one that matches the argument list in super(ttl, lngth). The next two statements initialize variables that only Movie has. Important Note: super() must be the first statement in the subclass's constructor. super() will be inserted into any constructor of the subclass as the first statement if you do not do not explicitly use a super constructor. If you have more than one constructor in the subclass you can use the super() with or without parameter as appropriate.
55
Using A Super Constructor (2)
An example. If the code looks like this: public Movie( String ttl, int lngth, String dir, String rtng ) { setTitle( ttl ); // initialize inherited variables setLength( lngth ); setAvailable( true ); director = dir; // initialize Movie variables rating = rtng; } Then the following insert takes place: super(); // inserted by compiler: parent's no-argument constructor director = dir; // initialize Movie variables Note: In our program the class definition for Video (the superclass) lacks a no-argument constructor. The proposed constructor (above) calls for such a constructor so it would cause a syntax error.
56
A Few Notes About The Default Constructor
The programmer can explicitly write a no-argument constructor for a class. If the programmer does not write any constructors for a class, then a no-argument constructor (called the default constructor) is automatically supplied. If the programmer writes even one constructor for a class then the default constructor is not automatically supplied. So: if you write a constructor for a class, then you must also write a no-argument constructor if one is expected. Look at Test2VideoStore.java
57
Inheritance Rules for Constructors
58
Overriding A Parent Method
In any object-oriented programming language, Overriding is a feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes. A child's method overrides a parent's method when it has the same signature as a parent method. Remember that the signature of a method is the name of the method and its parameter list. When overriding a method with the same signature you can change the return type under certain conditions. A non-primitive and A subclass of what the base class’s overridden method is returning (i.e. co-variant Return Type). Example – if a reference to a Video is returned in the superclass a reference to a Movie can be returned in the subclass method that is overriding Now the parent has its method, and the child has its own method with the same signature. Now look at Test3VideoStore.java and Movie3.java to see the overriding of toString() in Movie You can also incorporate super in the process to print out the common parts the same way.
59
Inheritance Rules For Overwritten Methods
60
private Variables and Methods In A Superclass
Superclass members declared as private are not inherited, although they are part of the subclass. Thus, a title, length and avail instance variable is allocated to all Movie objects, but methods of the Movie class cannot directly access title, length or avail directly. To set or get the value of title, length or avail, the Movie methods must call the inherited getXXX or setXXX methods, which are public methods. This simplifies maintenance because the Video class enforces the data validation rules for title, length or avail.
61
protected Variables and Methods In A Superclass
protected members are inherited by subclasses (like public members), while still being hidden from client classes (like private members). This means that the variables and methods that are protected can be directly accessed Also, any class in the same package as the superclass can directly access a protected field, even if that class is not a subclass. Disadvantage: Because more than one class can directly access a protected field, protected access compromises encapsulation and complicates maintenance. For that reason, we prefer to use private, rather than protected, for our instance variables.
62
A Few More Notes On protected Members
Declaring fields as private preserves encapsulation. Subclass methods call superclass methods to set the values of the fields, and the superclass methods enforce the validation rules for the data. However, calling methods incurs processing overhead. Declaring fields as protected allows them to be accessed directly by subclass methods. Classes outside the hierarchy and package must use accessors and mutators for protected fields. Advantage: protected fields can be accessed directly by subclasses, so there is no method-invocation overhead. Disadvantage: Maintenance is complicated because the subclass also needs to enforce validation rules. Recommendation: Define protected fields only when high performance is necessary. Avoid directly setting the values of protected fields in the subclass.
63
Inheritance Rules For Classes and Subclasses
64
The Object Class All classes have a parent class (have a super class) except one. The class at the top of the Java class hierarchy is called Object. If a class definition does not extend a parent class then it automatically has Object as a parent class. If a class definition does extend a parent class, then if the parent class does not extend a parent it automatically has Object as a parent class. And so on. Ultimately all classes have Object as an ancestor. This means that all classes in Java share some common characteristics. Those characteristics are defined in Object. For example, all classes have a toString() method because the class Object defines that method so all classes get it by inheritance. Of course, usually when you write a class you override the toString() method. Constructors for our classes have not mentioned Object . According to the rule, the compiler automatically does this: public Video( String ttl, int lngth ) { super(); // use the super class's constructor title = ttl; length = lngth; avail = true; } And Video automatically has what is in red done: class Video extends Object
65
The Java Hierarchy for Video
66
Programming Exercise 1 (Classes)
CellPhone and CellPhoneTester Wireless Solutions, Inc., is a business that sells cell phones and wireless service. You are a programmer in the company’s information technology (IT) department, and your team is designing a program to manage all of the cell phones that are in inventory. You have been asked to design a class that represents a cell phone. The data that should be kept as fields in the class are as follows: The name of the phone’s manufacturer will be assigned to the manufact field. The phone’s model number will be assigned to the model field. The phone’s retail price will be assigned to the retailPrice field. The class will also have the following methods: A constructor that accepts arguments for the manufacturer, model number and retail price. A setManufact method that accepts an argument for the manufacturer. This method will allow us to change the value of the manufact field after the object has been created, if necessary. A setModel method that accepts an argument for the model. This method will allow us to change the value of the model field after the object has been created, if necessary. A setRetailPrice method that accepts an argument for the retail price. This method will allow us to change the value of the retailPrice field after the object has been created, if necessary. A getManufact method that returns the phone’s manufacturer. A getModel method that returns the phone’s model number. A getRetailPrice method that returns the phone’s retail price. A toString method that prints out the phone’s manufacture, model and price. Write a program that creates a CellPhone object and tests all the methods
67
Programming Exercise 2 (1) - Aggregation
Modifying the CourseDemo and Course classes Download the 4 classes For this example the Instructor and TextBook classes remain unchanged. Relabel CourseDemo and Course as CourseDemoV2 and CourseV2 in the file and class name In CourseV2 Change the constructor by eliminating the TextBook variable. For an instance variable create an ArrayList of TextBook objects – remember to import ArrayList Create an void addTextBook(TextBook) method with appropriate code to add a TextBook to the ArrayList Modify toString so that it prints out each TextBook in the ArrayList
68
Programming Exercise 2 (2 ) - Aggregation
Modifying the CourseDemo and Course classes In CourseDemoV2 Create the Course as in current example (hard coded, but eliminate the TextBook from the constructor call) Read in the file name containing a list of text books for the course (you can download textbooks.txt). The format of the file has the format for each textbook on three lines containing: Title Author Publisher Create a Scanner to read in the file – Read in three lines Create a TextBook Call addTextBook to add a new text book for the course Note: A better model might have the Instructor adding the TextBook(s) for the course
69
Programming Exercise 3 Inheritance – Extending A class (1)
Extending the Game class Download the Game class from Lesson 12 Classwork and read its structure Create a subclass PCBasedGame Add three new instance values – minimum megabytes of RAM required, minimum number of disk megabytes required, (both as type int), and required gigahertz speed of processor (as a double) Create accessors and mutators for each new instance variable Create an overriding toString() method and equals() method – equals method is true if each pair of instance variables are equal Write a PCBasedClient class with the main program that does the following Reads in the description, required RAM MBs, disk MBs and Gigahertz speed for a PCBasedGame object pcbg1. Create a pcbg1 object Use toString to print out pcbg1 Reads in the description, required RAM MBs, disk MBs and Gigahertz speed for a PCBasedGame object pcbg2. Create a pcbg2 object Use toString to print out pcbg2 Use equals to check equality between the two games Use accessors and mutators to set all pcbg2 instance variable values to pcbg1 values Now use equals again to check between the two games
70
Programming Exercise 3 Inheritance – Extending A class (2)
Sample IO Please enter the game description for game one: Monopoly Please enter the required RAM MBs and Disk Size MBs for game one as type int: 24 120 Please enter the required CPU speed in Gigahertz for game one as a double: 32.7 Game Description: Monopoly Minimum configuration: RAM: 24 MB; hard disk: 120 MB; CPU GHZ Please enter the game description for game two: Scrabble Please enter the required RAM MBs and Disk Size MBs for game two as type int: 36 197 Please enter the required CPU speed in Gigahertz for game two as a double: 45.2 pcbg1 and pcbg2 are not equal pcbg1 and pcbg2 are now equal
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.