COP 3330 Exam 2 Review Chapter Sections 7 7.1 – 7.8 Topics Classes, static vs. instance, this, references vs. objects, inherited methods, overriding, scoping rules, method overloading, generic classes None None Aggregation 8 8.3 – 8.4, 8.8 – 8.11 Iterator, Array Processing, 2-D Arrays, Vector, Arraylist Collection Algorithms 9 9.1 – 9.2 Inheritance, Polymorphism, Visibility Modifiers How to study: 1) Go through both of your programs. Make sure you understand how they work. I may ask questions based on your homework assignments. 2) Look over all of the sample program presented in class. For this semester, these contain a more thorough breakdown of the material covered in class than the notes. 2) Read the class notes. Make sure you understand the ideas presented. 3) Read the sections denoted above. 4) Peruse the problems at the end of the appropriate chapters in the text and plan out how you would attack them. Exam Format Here are the different types of questions I will have: 1) Tracing: Either through code segments or of an entire program that uses a class. 2) Writing: You may have to write a main method that uses a class, or write class methods. 3) You may have to find mistakes in a piece of code. 4) Short Answer: Some of the reading goes over general concepts in fairly non-technical manner. I may ask questions on this material that require a single sentence answer. 5) Design Question: I may give you the basic idea of a class to be written and then ask you general questions about the design of the class. (What methods should be included? What should be private, public, etc.?) Exam Aids, etc. The exam will be open book and WILL NOT consist of a multiple choice section like the previous exam. Make sure to bring your text. Notes will not be allowed. Defining Classes Remember when you are defining a class, you need to define two parts: 1) instance variables (these dictate the structure of an object of the class.) 2) instance methods (these dictate what operations are allowed on an object of the class.) Generally instance variables are private, and all methods you want others to use are public. Other methods, such as the totalminutes method in the Time class need not be public. Remember that there are three types of variables you could have when dealing with instance methods: 1) instance variables 2) formal parameters 3) local variables Learn the difference between the three and do not call different types of variables with the same name. Remember that anytime you refer to an instance variable in an instance method, you are referring to the instance variable OF the object the method was called upon. Formal parameters are the information the method needs to complete it's task. Local variables are declared as necessary, such as loop indexes. Constructors The job of a constructor is to initialize an object of the class. Unlike C where you have to specifically allocate space for the object with a malloc call, (or something similar), java takes care of finding the appropriate memory automatically. All you have to do is initialize the components of the object. All constructors are public and must be named the same thing as the class. A constructor in the Time class has the signature: public Time(int h, int m); One important thing to keep straight in a constructor is the order of the assignment statements. In particular, the instance variables need to be assigned, so these need to be on the lefthand side and the formal parameters need to be on the right. Constructors are often overloaded, meaning that there are multiple ones defined with different parameter lists. The one instantiated depends on the number and types of the actual parameters. A default constructor is one that takes in no parameters. Inheriting Methods All classes in java are part of an inheritance structure. In particular, all classes inherit from the class Object. From there, we can have a longer “chain” of inheritance. In any inheritance relationship, the class from which another class inherits is known as the base/parent class. The class that does the inheriting is known as the sub/child class. The child class retains all characteristics of the parent class, plus can have some unique characteristics of its own. Thus, the Time class, which we defined in class, automatically inherits all of the characteristics of the Object class. For example, the Object class has a toString method. If there is no toString method declared in the Time class, then anytime the toString method is called on a Time object, it will actually run the toString method defined in the Object class. In essence, the Time class has inherited the toString method in this example. The other option would be to write a toString method in the Time class. Once we do this, if we call the toString method on a Time object, it will call the one defined in the Time class, overriding the toString method in the Object class. (The rule is that the method in the “nearest” class overrides all similar methods in previous parent classes.) It would be a good idea to take some of the examples shown in class and test out what occurs when a method is overridden and when it is not. toString The following method is defined in the Object class: public String toString(); It is frequently overridden in user-defined classes. The reason for this is as follows: Anytime someone tries to print out an Object, what java automatically does is call toString() on that Object and just prints out what that method returns. Thus, if t is a time object and you run System.out.println(t); //You are implicitly running System.out.println(t.toString()); compareTo This method is necessary to implement the Comparable interface. We will talk about interfaces later, but the basic idea is that to implement an interface, you must write certain methods in your class. To implement Comparable, you must write a method with the following signature: public int compareTo(Object o); Furthermore, the method should work as follows: It should return a negative integer if the current object comes before o. It should return 0 if the two objects are equal and it should return a positive integer if the current object comes after o. Notice that the method takes in an Object. Thus, you must cast o to the appropriate type in order to access any components of the actual object that gets passed into the method. static vs. instance static means, “belongs to the class.” instance means, “belongs to the object.” An instance method MUST BE called on an object of that class. A static method is always called CLASSNAME.method(<parameter list>); because it just belongs to the class and does NOT operate on any object inherently. An instance variable belongs to the object, whereas only one copy of a static variable ever exists, regardless of how many objects of a class are instantiated. Visibility modifiers For right now, we are only using two of them: Private: Accessible only inside of the class. Protected: Accessible inside the class, subclass and package. Public: Accessible anywhere. Usually, instance variables are private while most instance methods are public. The goal here is to hide the representation of the data from the user. The public methods are the only means by which the user can manipulate objects they create. We can restrict the types of operations the user can perform by restricting the public methods we give them access to. Aggregation When we design a set of classes for an application, one of the relationships between classes is aggregation. This relationship is when one class contains OR HAS-A object of another class. For example, a Lemonade Object is comprised of several components, one of which is a BankAccount object. In many instances it makes sense to create classes with an aggregation relationship. (If you created a Car object, it would ideally contain/have several wheel objects.) It's important to recognize and understand the difference between an aggregation relationship and an inheritance relationship. The best way to internalize these concepts is to look at examples with several classes and consider how you would extend them. Iterator If you want to "go through" each element in a Java collection or array, you can do so as follows: for (Object o : collectionName) { // Use o in here } The first item inside of the loop is the type of item being stored in the collection. The second item is the variable name temporarily given for an arbitrary object in the collection. This is followed by a colon and then the name of the collection through which you want to iterate. Inside the loop, instead of having to index into an array, just use the given variable name in the body of the loop and those actions will be performed on each element in the collection as the loop executes. 2-Dimensional Arrays Technically, a 2 dimensional array is an array of arrays. It is possible to allocate space for the array references, without allocating space for each array. Furthermore, it is possible to allocate space for references to objects without allocating space for each object. Once the array is created, it is indexed just like a 2 dimensional array in C. Object[][] vals; // vals is a reference to a 2D array vals = new Object[10][]; // we've allocated vals to point to an //array that stores 10 array references. for (int i=0; i<vals.length; i++) vals[i] = new Object[i+1]; // allocated space for each array // individually; for (int i=0; i<vals.length; i++) for (int j=0; j<vals[i].length; j++) vals[i][j] = new Object(); // create each individual Object. Vector, ArrayList Java provides these classes that manage collections. Generally they are quite handy. They allow you to add elements, search for elements and remove elements from a collection. It's important to remember some syntactic issues when using these. If you create a Vector of Object for example, sometimes you may need to cast the value returned from a method to the proper type. No casting is necessary to add an Object into a collection. Remember to use the Generic construction when using these classes: ArrayList<String> s = new ArrayList<String>(); Collections Algorithms Java provides some very nice methods to help manipulate collections. Here are some of the algorithms provided: Sorting, Max, Min, Reverse, and Shuffle All of the methods are static, thus, they are called from the class and the collection is always passed in as a parameter. In order to sort, the type of objects stored in the collection must implement Comparable. Basics of Inheritance An inherited class is defined as follows, using the key word extends: public class ThreeDimensionalPoint extends Point { … } In the example above, Point is known as the base/parent/super class, and ThreeDimensionalPoint is Point's subclass. (Alternatively, Point is known as the base class from which ThreeDimensionalPoint inherits. Also, there is an IS-A relationship here – a ThreeDimensionalPoint object IS A Point object as well.) A subclass inherits all the characteristics of the superclass. Thus, all public methods in the superclass are valid to be run on objects of the subclass. In the typical case, the subclass adds at least one instance variable, separate from those it inherited from the superclass. In the example in the text, ThreeDimensionalPoint has its own instance variable z, and inherits x and y from Point. In the typical case, a subclass just uses some of the methods in its superclass, but overrides other methods. To override a method, you must define a method with the same signature as one in the superclass in the subclass. The purpose of this is so that if you have a ThreeDimensionalPoint object, you end up running a different method on it than if you just had a Point object. The method call super() When overriding a method in the superclass, you have the option of calling the corresponding method from the superclass. To do this, instead of using "this" just use the name "super". For all methods except for constructor, you would call, super.methodname(). Pass the parameters you need/want to pass to the corresponding method in the superclass. Constructors All constructors in the subclass will automatically call the default constructor in the base class if there is NO EXPLICIT call to the base class constructor. The other option is to make an explicit call to the superclass constructor using "super". In this case, you control which of the constructors in the superclass gets called. (Here, the method call is just super, not super.methodname()) The rationale behind this is that you MUST build the base object first before building any of the rest of it to create the subclass specialization. Reasons to use Inheritance, instead of just adding to one class Putting all the functionality into one class may make it difficult to understand, or more difficult to use for simple things. (For example, sometimes you want to use points in 2 dimensions, sometimes in three. By incorporating inheritance, you make the use of both seamless. If you didn't, when wanting a 2-D point, you'd have to always just set z=0 and deal with that extra component.) Polymorphism Definition: A code expression can invoke different methods depending on the type of objects using the code. Thus, polymorphism allows the same exact method call to invoke different methods. Here's the key: In the code, we always use references. But, those references can refer to any object of the class of the reference, OR any SUBCLASS (direct or indirect) of the class of the reference. So, for example, we have a ColoredPoint class that inherits from Point, and a ThreeDColoredPoint class that inherits from ColoredPoint, a Point reference could refer to a Point object, a ColoredPoint object, or a ThreeDColoredPoint object. Java dynamically determines the actual exact class of the object and uses that information when deciding what method to invoke, when there are options from multiple classes. Rule 1: First look for the appropriate method IN the actual exact class of the object. If it's not there, then look in the direct superclass. If it's not there, continue up the inheritance structure. Rule 2: For a match to occur, the name, number of parameters, and types of corresponding parameters must match. Remember, the type match is NOT polymorphic. Thus, if a parameter is a reference from a base class, but that reference is referring to an object of the subclass, and that subclass is the parameter type, then this will NOT be considered a match. Visibility Modifier Rules Member Restriction public protected default private this Subclass Package General X X X X X X X X X X instanceof operator The instanceof operator is used in Boolean expressions as follows: reference instanceof Class This expression is true if the reference to the left of the operator is referring to an object that belongs in the class designated to the right of the operator. It doesn't have to be the exact class. Thus, if the variable pt is a Point reference, and it was referring to a ThreeDColoredPoint object, then the expressions pt instanceof Point pt instanceof ColoredPoint pt instanceof ThreeDColoredPoint would all evaluate to true. But if pt referred to a ColoredPoint object, then the first two would be true and the last one would be false.