Presentation is loading. Please wait.

Presentation is loading. Please wait.

LESSON 4 Reviewing Java Implementation Of OO Principles – Part 2

Similar presentations


Presentation on theme: "LESSON 4 Reviewing Java Implementation Of OO Principles – Part 2"— Presentation transcript:

1 LESSON 4 Reviewing Java Implementation Of OO Principles – Part 2
Abstract Classes, Polymorphism, Interfaces 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 Abstract Classes Polymorphism Interfaces

4 Object-Oriented Software Development In Java (Part 2)

5 Abstract Classes

6 Abstract Classes An abstract class in Java is a class that is never instantiated. Its purpose is to be a parent to several related classes. The children classes inherit from the abstract parent class. It is defined like this: abstract class ClassName { // definitions of methods and variables } Access modifiers such as public can be placed before abstract. Even though it can not be instantiated, an abstract class defines methods and variables that children classes inherit, as we will shortly describe

7 A Hierarchy With abstract classes
You can have a hierarchy of several levels before getting to the non-abstract classes Vehicle AUDI FORD HONDA FORDCAR FORDTRUCK FORDSUV FUSION MUSTANG FOCUS

8 The Structure Of An Abstract Class
A simple framework for abstraction. Note that the method has no body abstract class Card { protected String recipient; // name of who gets the card public abstract void greeting(); // abstract greeting() method - There is no body } Since no constructor is defined in Card the default no-argument constructor is automatically supplied by the compiler. However, this constructor cannot be used directly because no Card object can be constructed. – Why? Because abstract classes can’t be used to create objects.

9 Extending An Abstract Class (1)
Below is an example that extends Card class Holiday extends Card { public Holiday( String r ) recipient = r; // recipient in Card is protected, so this works } public void greeting() System.out.printf("Dear %s\n" , recipient); System.out.printf("Season's Greetings!\n"); Look at Card.java, Holiday.java, CardTester.java, CardTesterV2.java to see how we can instantiate a Holiday Card with different greetings See Card.java, Holiday.java, Valentine.java, Birthday.java and CardTesterV3.java to demonstrate how you can create multiple classes from a single abstraction, and then create objects from any of those classes

10 Extending An Abstract Class (2)
The class Holiday is not an abstract class. Objects can be instantiated from it. Its constructor implicitly calls the no-argument constructor in its parent, Card, which calls the constructor in Object. So even though it has an abstract parent, a Holiday object is just as much an object as any other. Notes: Holiday inherits the abstract method greeting() from its parent. Holiday must define a greeting() method that includes a method body (statements between braces). The definition of greeting() must match the signature given in the parent. If Holiday did not define greeting(), then Holiday must be declared to be an abstract class. This would make it an abstract child of an abstract parent.

11 Abstract Methods An abstract method has no body.
It declares an access modifier, return type, and method signature followed by a semicolon. It has no statements. A non-abstract child class inherits the abstract method and must define a non-abstract method that matches the abstract method. Abstract classes can (but don't have to) contain abstract methods. Also, an abstract class can contain non-abstract methods, which will be inherited by the children. An abstract child of an abstract parent does not have to define non-abstract methods for the abstract signatures it inherits. This means that there may be several steps between an abstract base class to a child class that is completely non-abstract. You don’t need to define each method the first step down.

12 A UML Depiction With An abstract class With Some abstract Methods
+t0String(): String +getArea(): double +getPerimeter(): double +t0String(): String +getArea(): double +getPerimeter(): double In the UML diagram, abstract classes and methods are italicized

13 Defining An Abstract Method
To declare a method as abstract, include the abstract keyword in the method header, and end the header with a semicolon: accessModifier abstract returnType methodName( argument list ); Note: The semicolon at the end of the header indicates that the method has no code. We do not use opening and closing curly braces.{}

14 Method Signature Quick Reminder: A signature looks like this:
someMethod( int, double, String ) The return type is not part of the signature. The names of the parameters do not matter, just their types. The name of a method is not enough to uniquely identify it. There may be several versions of a method, each with different parameters. The types in the parameter are needed to specify which method you want.

15 Restrictions When Defining Abstract Methods
An abstract method definition consists of: optional access modifier (public, private, and others), the reserved word abstract, the type of the return value, a method signature, a semi-colon. – no braces for a body abstract methods can be declared only within an abstract class. An abstract method must consist of a method header followed by a semicolon. abstract methods cannot be called. abstract methods cannot be declared as private or static. A constructor cannot be declared abstract.

16 Polymorphism

17 What Is Polymorphism? An important concept in inheritance is that an object of a subclass is also an object of any of its superclasses. That concept is the basis for an important OOP feature called polymorphism. Polymorphism means "having many forms." In Java, it means that one variable might be used with several objects of related classes at different times in a program. Polymorphism simplifies the processing of various objects in the same class hierarchy because we can use the same method call for any object in the hierarchy using a superclass object reference.

18 An Intuitive Introduction To Polymorphism
University Community Students Faculty Fine Arts Faculty Physics Faculty Computer Science Faculty Administrators

19 Discussion Of The University Hierarchy
Could you add a Faculty member to the list of the University Community without problem? Could it work the opposite way? This is what polymorphism is about, the ability to organize and call objects based on their parents. You couldn’t put a Fine Arts Faculty member in the Computer Science Faculty List. So when you take an object off a higher level list you may need to determine what kind of lower level object it actually is.

20 Using Polymorphism To use polymorphism, these conditions must be true:
The classes are in the same hierarchy. All subclasses override the same method(s). In the prior example that means that if getCredentials() was a method of UniversityCommunity then if any one of Student, Faculty and administrator overrode the method, then all would have to. Otherwise can’t use polymorphism. A subclass object reference is assigned to a superclass object reference. The superclass object reference is used to call the overridden method.

21 An Example Of Polymorphism
In the example below we create a variable card of type Card We can now use this variable for any subclass of that superclass public class CardTesterV4 { public static void main ( String[] args ) Card card = new Holiday( "Amy" ); card.greeting(); //Invoke a Holiday greeting() card = new Valentine( "Bob", 3 ); card.greeting(); //Invoke a Valentine greeting() card = new Birthday( "Cindy", 17 ); card.greeting(); //Invoke a Birthday greeting() }

22 Snap Check 1 Here are some variable declarations: Card c; Birthday b;
Valentine v; Holiday h; Which of the following are correct given our prior class definitions? c = new Valentine("Debby", 8); b = new Valentine("Elroy", 3); v = new Valentine("Fiona", 3); h = new Birthday ("Greg", 35);

23 Snap Check 1 Answers Card c; Birthday b; Valentine v; Holiday h; c = new Valentine("Debby", 8); //OK b = new Valentine("Elroy", 3); //WRONG v = new Valentine("Fiona", 3); //OK h = new Birthday ("Greg", 35); //WRONG

24 Snap Check 2 Given the definitions below and the
Hierarchy to the left: Rodent rod; Rat rat; Mouse mou; Fill in the chart code section OK or Not? rod = new Rat(); rod = new FieldMouse(); mou = new Rat(); mou = new Rodent(); rat = new Rodent(); rat = new LabRat(); rat = new FieldMouse(); rat = new Mouse();

25 Snap Check 2 Answers Given the definitions below and the
Hierarchy to the left: Rodent rod; Rat rat; Mouse mou; Fill in the chart code section OK or Not? rod = new Rat(); OK rod = new FieldMouse(); mou = new Rat(); Wrong mou = new Rodent(); rat = new Rodent(); rat = new LabRat(); rat = new FieldMouse(); rat = new Mouse();

26 Extending Classes and Polymorphism
class YouthBirthday extends Birthday { public YouthBirthday ( String r, int years ) super ( r, years ) } // additional method---does not override parent's method – Different Signature public void greeting( String sender ) super.greeting(); System.out.printf("How you have grown!!\n\n"); System.out.printf("Love, %s\n”, sender); See Card.java, Birthday.java, YouthBirthday.java, AdultBirthday.java, CardTesterV5.java

27 Referencing Subclass Objects with Subclass vs Superclass Reference – A Deeper Explanation (1)
There are two approaches to refer to a subclass object. Both have some advantages/disadvantages over the other. The declaration affect is seen on methods that are visible at compile-time. First approach (Referencing using Superclass reference): A reference variable of a superclass can be used to refer to any subclass object derived from that superclass. If the methods are present in Superclass, but overridden by Subclass, it will be the overridden method that will be executed. Second approach (Referencing using subclass reference) : A subclass reference can be used to refer its object. See Programs Bicycle.java, MountainBike.java, TestBikes.java

28 Referencing Subclass Objects with Subclass vs Superclass Reference – A Deeper Explanation (2)
The object of MountainBike class is created which is referred by using subclass reference ‘mb1’. MountainBike mb1 = new MountainBike(3, 100, 25); Using this reference we will have access both parts(methods and variables) of the object defined by the superclass or subclass. See below image for clear understanding.

29 Referencing Subclass Objects with Subclass vs Superclass Reference – A Deeper Explanation (3)
Now we again create object of MountainBike class but this time it is referred by using superclass Bicycle reference ‘mb2’. Using this reference we will have access only to those parts(methods and variables) of the object defined by the superclass. Bicycle mb2 = new MountainBike(4, 200, 20);

30 Referencing Subclass Objects with Subclass vs Superclass Reference – A Deeper Explanation (4)
If there are methods present in super class, but overridden by subclass, and if object of subclass is created, then whatever reference we use(either subclass or superclass), it will always be the overridden method in subclass that will be executed. In our example, we have seen that by using reference ‘mb2’ of type Bicycle, we are unable to call subclass specific methods or access subclass fields. In general, a superclass reference cannot reference subclass specific methods This problem can be solved using type casting in java. For example, we can declare another reference say ‘mb3’ of type MountainBike and assign it to ‘mb2’ using typecasting. // declaring MountainBike reference MountainBike mb3; // assigning mb3 to mb2 using typecasting. mb3 = (MountainBike)mb2;

31 Referencing Subclass Objects with Subclass vs Superclass Reference – A Deeper Explanation (5)
Summary Of Polymorphic Reference Usage – subclass v. superclass Advantage We can use superclass reference to hold any subclass object derived from it. Disadvantage By using superclass reference, we will have access only to those parts(methods and variables) of the object defined by the superclass. For example, we can not access seatHeight variable or call setHeight(int newValue) method using Bicycle reference in above first example. This is because they are defined in subclass not in the superclass.

32 The instanceof Operator (1)
We’ve already been using this operator in our equals() methods. Look at the example below: Object obj; YouthBirthday ybd = new YouthBirthday( "Ian", 4 ); String str = "Yertle"; obj = ybd; if ( obj instanceof YouthBirthday ) ((YouthBirthday)obj).greeting(); else if ( obj instanceof String ) System.out.printf(“%s\n”, (String)obj );

33 The instanceof Operator (2)
The format of instance of is: variable instanceof ClassName A type casting is used to tell the compiler what is really in a variable that itself is not specific enough. You have to tell the truth. In a complicated program, a reference variable might end up with any of several different objects, depending on the input data or other unpredictable conditions. The instanceof operator evaluates to true or false depending on whether the variable refers to an object of its operand. Also, instanceof will return true if variable is a descendant of Class. It can be a child, a grandchild, a greatgrandchild, or ... of the class.

34 Interfaces

35 What Is An interface In Java (1)
An interface describes aspects of a class other than those that it inherits from its parent. An interface is a set of requirements that the class must implement. An interface is a list of constants and method headers. Prior to Java 8 the methods were not implemented in the interface (there is no method body), although the word abstract is not used. Starting with Java 8 default methods are allowed (to be discussed shortly). A class that implements an interface must implement all of the methods listed in the interface.

36 What Is An interface In Java (2)
As we have said, a class can extend only one parent class to inherit the methods and instance variables of that parent. A class can also implement multiple interfaces to gain additional methods and constants. However, the methods in the interface must be implemented (explicitly written) as part of the importing class definition. Default methods don’t need to be reimplemented The interface is a list of requirements that the class definition must explicitly meet (through written code, not through inheritance). Note: Each interface can contain one or more methods. For example, a class Car might extend the Vehicle class. Inheritance then gives it all the public/protected methods and instance variables of Vehicle. If Car also implements the Taxable interface, then its definition must contain code for all the methods listed in Taxable.

37 Defining An interface (1)
An interface has the following form: interface InterfaceName { constant definitions method headers (without implementations). Default methods } As previously described, a method header is an access modifier, a return type, the method name, a parameter list followed by a semicolon. You can put an interface in its own source file or include it with other classes in a source file. In either case, the source file ends with the extension .java The methods in an interface are public by default, so you can omit public from the method headers. The methods can never be private and cannot be protected prior to Java 9 An interface looks somewhat like a class definition. But no objects can be constructed from it. However, you can define a class that implements an interface, and once you have done that you can construct objects of that class (via polymorphism)

38 Defining An interface (2)
A class implements an interface by doing this: class SomeClass extends SomeParent implements InterfaceName1, InterfaceName2, …. { } Rules A class extends just one parent, but may implement multiple interfaces. A method in an interface cannot be made private. A method in an interface is public by default. The constants in an interface are public static final by default. Recall that final means that the value cannot change as the program is running. 

39 Example Of Defining An interface
Look at these two examples: Example 1: interface MyInterface { public static final int ACONSTANT = 32; // a constant public static final double PI = ; // a constant public void methodA( int x ); // a method header public double methodB(); // a method header } Example 2: int ACONSTANT = 32; // a constant (public static final, by default) double PI = ; // a constant (public static final, by default) void methodA( int x ); // a method header (public, by default) double methodB(); // a method header (public, by default) The second interface (above) is the preferred way to define an interface. The defaults are assumed and not explicitly coded.

40 Snap Check What is wrong with the following interface?
interface SomeInterface { public final int x = 32; public double y; public double addup( ); }

41 Rules For Implementing An interface
A class that implements an interface must implement each method in the interface. Methods from the interface must be declared public in the class. This is changed in Java v9, but most computers at CSUDH are still running Java 8, so we will stick with public interfaces Constants from the interface can be used as if they had been defined in the class. Constants should not be redefined in the class. Any number of classes can implement the same interface. The implementations of the methods listed in the interface can be different in each class. A subclass inherits the methods implemented in its superclass, so we don’t use the word implement again if its been implemented, although we can still override any of the methods.

42 A Recent Change In interface
Before Java 8, interfaces could have only abstract methods. The implementation of these methods has to be provided in a separate class. So, if a new method is to be added in an interface, then its implementation code has to be provided in the class implementing the same interface. To overcome this issue, Java 8 has introduced the concept of default methods which allow the interfaces to have methods with implementation without affecting the classes that implement the interface. The default methods were introduced to provide backward compatibility so that existing interfaces can use the lambda expressions without implementing the methods in the implementation class. default is used as a modifier of the method A default method can be accessed via the object even if it isn’t overwritten in the class A default method can still be overridden Default methods are also known as defender methods or virtual extension methods. See VehicleActions.java, Car.java, CarInterfaceTester.java

43 Static Methods In Interfaces
Another feature that was added in JDK 8 is that we can now define static methods in interfaces which can be called independently without an object. Note: these methods are not inherited. These methods are accessed as follows: InterfaceName.methodName(p1, p2, ..)

44 An interface Is A Contract
When a class implements an interface, it is agreeing to provide all of the methods that are specified in the interface. It is often said that an interface is like a “contract,” and when a class implements an interface it must adhere to the contract.

45 UML With An interface (2)
Dotted lines indicate implements rather than extends Below is a real example from the Java language

46 UML With An interface (2)
Italicized items are abstract

47 Sample Problem – Taxing Goods In A Store
Let us create a database program for a store. The store sells: Goods, each of which has the attributes: description price The types of goods are: Food — with an attribute calories. Food objects are not taxable. Toy — with an attribute minimumAge. Toy objects are taxable. Book — with an attribute author. Book objects are taxable. There are many things that are taxable that are not goods, such as services or entertainment. Also, not all goods are taxable. So we want to have the concept taxable as a separate concept, not part of the concept of Goods, since not all Goods are taxed. Here is what the concept Taxable looks like: A Taxable item, has a taxRate of 6 percent, has a calculateTax() method. When implemented in Java, these concepts will appear as a class hierarchy and as an interface.

48 Snap Check Fill in this chart: Concept
Parent Class, Child Class, or Interface? Goods  Food  Toy  Book  Taxable

49 Snap Check Answers Concept Parent Class, Child Class, or Interface?
Goods  Parent Food  Child Toy  Book  Taxable Interface

50 An Example Using interface
Look at the files Goods.java, Food.java, Taxable.java (an interface) Book.java, Toy.java, TestStore.java TestStoreArray.java and TestStoreArrayList.java also exhibit rules of polymorphism

51 Interface As A Type Just as with classes, an interface can be used as a data type for a reference variable. Since Toy and Book implement Taxable, they can both be used with a reference variable of type Taxable The Taxable interface tells the compiler that all Taxable objects will have a calculateTax() method, so that method can be used with these variables. Note that this is another example of polymorphism public class TestStore2 { public static void main ( String[] args ) Taxable item1 = new Book ( "Emma", 24.95, "Austen" ); Taxable item2 = new Toy ( "Legos", 54.45, 8 ); System.out.printf("Tax is: %.2f\n", item1.calculateTax()); System.out.printf("Tax is: %.2f\n", item2.calculateTax()); } } See TestStore2.java

52 Type Casting With Classes
We have already used type casting in our equals() methods If you executed the following program you will get an error: public class TestStore3 { public static void main ( String[] args ) Taxable item1 = new Book ( "Emma", 24.95, "Austen" ); System.out.printf( "Tax on item 1 %.2f\n”, item1.calculateTax() ); System.out.printf( "Author: %s\n", item1.getAuthor() ); } Why? Not all taxable items have access to the term author. If you want item1 to act like a Book you need to cast it System.out.printf( "Author: %s\n", ((Book))item1.getAuthor() ); See TestStore3.java TestStore4.java shows another example of casting

53 Hierarchies Of Interfaces
An interface can be an extension of another interface (but not an extension of a class): public interface ExciseTaxable extends Taxable { double extraTax = 0.02; double calculateExtra(); } A complex hierarchy of interfaces can be constructed using this feature.

54 Summary Of Rules For Polymorphism With Interfaces (1)
Java allows you to create reference variables of an interface type. An interface reference variable can reference any object that implements that interface, regardless of its class type. The following discussion is based on: RetailItem.java, CompactDisc.java, DvdMovie.java and PolymorphicInterfaceDemo.java In the example code, two RetailItem reference variables, item1 and item2, are declared. The item1 variable references a CompactDisc object and the item2 variable references a DvdMovie object. When a class implements an interface, an inheritance relationship known as interface inheritance is established. Both a CompactDisc object is a RetailItem, and a DvdMovie object is a RetailItem.

55 Summary Of Rules For Polymorphism With Interfaces (2)
A reference to an interface can point to any class that implements that interface. You cannot create an instance of an interface. RetailItem item = new RetailItem(); // ERROR! When an interface variable references an object: Only the methods declared in the interface are available, Explicit type casting is required to access the other methods of an object referenced by an interface reference.

56 Anonymous Classes And interfaces
An inner class is a class that is defined inside another class. An anonymous inner class is an inner class that has no name. An anonymous inner class must implement an interface, or extend another class. Useful when you need a class that is simple, and to be instantiated only once in your code. See: IntCalculator.java , AnonymousClassDemo.java

57 Functional Interfaces and Lambda Expressions – An Introduction

58 Functional Interfaces
A functional interface is an interface that has one abstract method. You can use a special type of expression, known as a lambda expression, to create an object that implements a functional interface. Both the functional interface and lambda expression are new in Java 8. interface IntCalculator { int calculate(int number); }

59 Lambda Expressions Because IntCalculator is a functional interface, we do not have to go to the trouble of defining a class that implements the interface. Instead, we can use a lambda expression to create an object that implements the interface, and overrides its abstract method. Note: To use a lambda expression the interface file must be there. It actually gets compiled into a class when we compile the main class or another class that uses it. You can think of a lambda expression as an anonymous method, or a method with no name. Like regular methods, lambda expressions can accept arguments and return values. Here is the general format of a simple lambda expression that accepts one argument, and returns a value: (parameterList) -> expression or (parameterList) -> {statements} In this general format, the lambda expression begins with a parameter variable, followed by the lambda operator (->), followed by an expression that has a value. Here is an example: x -> x * x or (x, y) -> {return x+y} See LambdaDemo.java, LambdaDemo2.java, IntCalculator.java

60 Rules When Using Lambda Expressions (1)
Lambda Expressions That Do Not Return a Value If a functional interface’s abstract method is void (does not return a value), any lambda expression that you use with the interface should also be void. Here is an example: x -> System.out.printf(“%d\n”, x); This lambda expression has a parameter, x. When the expression is invoked, it displays the value of x. Lambda Expressions with Multiple Parameters If a functional interface’s abstract method has multiple parameters, any lambda expression that you use with the interface must also have multiple parameters. To use more than one parameter in a lambda expression, simply write a comma-separated list and enclose the list in parentheses. Here is an example: (a, b) -> a + b; This lambda expression has two parameters, a and b. The expression returns the value of a + b.

61 Rules When Using Lambda Expressions (2)
Lambda Expressions with No Parameters If a functional interface’s abstract method has no parameters, any lambda expression that you use with the interface must also have no parameters. Simply write a set of empty parentheses as the parameter list, as shown here: () -> System.out.printf(); When this lambda expression is invoked, it simply prints a blank line. Explicitly Declaring a Parameter’s Data Type You do not have to specify the data type of a lambda expression’s parameter because the compiler will determine it from the interface’s abstract method header. However, you can explicitly declare the data type of a parameter, if you wish. Here is an example: (int x) -> x * x; Note that the parameter declaration (on the left side of the -> operator) must be enclosed in parentheses. Here is another example, involving two parameters: (int a, int b) -> a + b;

62 Rules When Using Lambda Expressions (3)
Using Multiple Statements in the Body of a Lambda Expression You can write multiple statements in the body of a lambda expression, but if you do, you must enclose the statements in a set of curly braces, and you must write a return statement if the expression returns a value. Here is an example: (int x) -> { int a = x * 2; return a; }; Accessing Variables Within a Lambda Expression A lambda expression can access variables that are declared in the enclosing scope, as long as those variables are final, or effectively final. An effectively final variable is a variable whose value is never changed, but it isn’t declared with the final key word.

63 Programming Exercise 1 – An abstract class
Extending the abstract class Shape Create an abstract superclass Shape. Shape has two abstract methods, perimeter and area, and a final constant field named PI. Create two non-abstract subclasses, one encapsulating a Circle, the other a Rectangle. Rectangle has two additional attributes, length and width of type double. Circle has one additional attribute, its radius of type double. Write a TestShape class with a main method that tests out the above. Read in the length and width of a rectangle and print out the perimeter and area. Read in the radius of a rectangle and print out the perimeter (circumference) and area.

64 Programming Exercise 2 – Polymorphism
Implement the following classes Abstract Vehicle class Write an abstract superclass encapsulating a Vehicle. A Vehicle has two attributes = owner (String) and wheels (an int) Write accessor and mutator methods for both attributes. Write methods for a toString that includes the owner and the number of wheels. Write an equals() method that is true if both attributes are equal when comparing two vehicles. Bike class Write a class encapsulating a Bike that extends Vehicle that only has a constructor and no overriding methods. The Bike only has an owner and wheels. MotorizedVehicle class Write a class encapsulating a MotorizedVehicle that extends Vehicle. There is one extra attribute for volume displacement. There is one extra accessor and one extra mutator. There is one extra method computing horsepower which is the volume displacement times the number of wheels. You should also override the to String() and equals() method, taking into account the third attribute VehicleClient class which includes the main method. Read in 4 different vehicles, a mix of 2 bikes and 2 motorized vehicles into an ArrayList of type Vehicle, each with different values for the attributes. reads in the attributes for two Motorized objects. Uses the toString() method to print out the 4 vehicles as appropriate Use the equals() to compare the two motorized vehicles and two bicycles, print out results It set the second motorized vehicle’s attributes equal to the first’s and retest with the equals() method.

65 Programming Exercise 3 – Adding More interfaces
Copy Goods.java, Food.java, Book.java, Toy.java and Taxable.java Create a new interface called Returnable with a boolean method canReturn: boolean canReturn(double threshold); Implement Returnable in Book and in Toy to return true if the value of the Book is greater than a threshold (call these classes Book2 and Toy2) Modify a version of TestStore.java (call it TestStore5.java) to check this feature for each of the two classes obtaining both true and false features. Read in a threshold for each class.


Download ppt "LESSON 4 Reviewing Java Implementation Of OO Principles – Part 2"

Similar presentations


Ads by Google