Chapter 13: Inheritance and Abstract Classes

Réussis tes devoirs et examens dès maintenant avec Quizwiz!

13.34 Trace the program carefully and show the output of the following code. Rational r1 = new Rational(1, 2); Rational r2 = new Rational(1, -2); System.out.println(r1.add(r2));

0/4

13.30 Show the output of the following code? Rational r1 = new Rational(-2, 6); System.out.println(r1.getNumerator()); System.out.println(r1.getDenominator()); System.out.println(r1.intValue()); System.out.println(r1.doubleValue());

1 3 0 .333333333333

13.6 Show the output of the following code. public class Test { public static void main(String[] args) { Number x = 3; System.out.println(x.intValue()); System.out.println(x.doubleValue()); } }

3 3.0

13.25 Show the output of the following code: ArrayList<String> list = new ArrayList<>(); list.add("New York"); ArrayList<String> list1 = list; ArrayList<String> list2 = (ArrayList<String>)(list.clone()); list.add("Atlanta"); System.out.println(list == list1); System.out.println(list == list2); System.out.println("list is " + list); System.out.println("list1 is " + list1); System.out.println("list2.get(0) is " + list2.get(0)); System.out.println("list2.size() is " + list2.size());

A syntax error is reported because clone() is protected in Object. To enable cloning, do two things: (1) override clone() in the class for the object to be cloned; (2) implement java.lang.Cloneable for the class.

13.26 What is wrong in the following code?What is wrong in the following code? public class Test { public static void main(String[] args) { GeometricObject x = new Circle(3); GeometricObject y = x.clone(); System.out.println(x == y); } }

A syntax error is reported because clone() is protected in Object. To enable cloning, do two things: (1) override clone() in the class for the object to be cloned; (2) implement java.lang.Cloneable for the class.

Number Class

Abstract superclass for double, int, float, long, short, byte, BigInteger, BigDecimal

13.16 Show the error in the following code: interface A { void m1(); } class B implements A { void m1() { System.out.println("m1"); } }

All methods defined in an interface are public. When a class implements the interface, the method must be declared public. The visibility cannot be reduced.

Abstract Class

An abstract class cannot be used to create objects, but contains abstract methods that are implemented in concrete subclasses. @denoted by abstract keyword in class header EX: public abstract class GeometricObject @constructor is defined as protected, because only a subclass can instantiate the object @abstract class can not be instantiated using the new operator @does not have to contain abstract methods

Interface

An abstract for defining common behavior for classes, including unrelated classes. @contains only constants and abstract methods @all methods must be public and implementing overrides cannot reduce visibility @distinguished by keyword interface EX: public interface Edible{ } @UML notation interface name and method names are italicized and is connected with a dashed line and open triangle to the interface @multiple interfaces can be implemented at the same time and are separated by a comma in the class header @all variables must be public static final

13.4 Why do the following two lines of code compile but cause a runtime error? Number numberRef = new Integer(0); Double doubleRef = (Double)numberRef;

At runtime, JVM attempts to convert numberRef to a Double object, but numberRef is an instance of Integer, not Double.

Refactoring

Bunch of classes that have redundancies that can be factored into common superclasses

13.20 You can define the compareTo method in a class without implementing the Comparable interface. What are the benefits of implementing the Comparable interface?

By implementing the Comparable interface, the object of the class can be passed to a method that requires a Comparable type.

13.35 Class Design Guidelines

Cohesion - should describe a single entity and all methods support a coherent purpose. Consistency - Follow standard style and naming conventions. Encapsulation - make private to hid data form direct access by clients Clarity - a clear contract that is easy to explain and to understand Completeness - should take dynamic users in mind and create cohesive methods Instance vs. Static - methods not dependant on a specific instance should be static; always reference static variables and mthods from a class name to improve readibility and avoid errors Inheritance vs Aggregation - inheritance is an "is-a" relationship and aggregation is a "has-a" relationship Interfaces vs. Abstract classes - Strong "is-a" relationship should be an abstract class while a weak is-a relationship should be an interface. Interfaces should be uses for unrelated classes with similar properties as needed and is much more flexible.

Cloneable Interface

Contains constants and abstract method to allow the copy of an object in implement. @clone() default method performs a shallow copy.

Redundant Variables and Data in Bag Classes

DEFAULT_CAPACITY, self._size, and self._items are the same and refer to the same types of objects

Abstract Class

Defines data and methods common to all subclasses, but is rarely instatiated

Comparable Interface

Defines the compareTo() method for comparing objects. This allows one to choose the properties of the objects rather than their reference location. @Comparable is a GENERIC interface defined by <E> @compareTo() determines the order of this object wiht the specified object o and returns a negative integer, zero or a positive integer if this object is less than, equal to or greater than. @compareTo() should be consistent with equals override

Factoring

Eliminate redundant data and code by __ them up the hierarchy

13.23 What would happen if the House class (defined in Listing 13.11) did not override the clone() method or if House did not implement java.lang.Cloneable.?

If the House class does not override the clone() method, the program would receive a syntax error because clone() is protected in java.lang.Object. If House does not implement java.lang.Cloneable, a CloneNotSupportedException would occur when invoking super.clone().

AbstractCollection

Includes data and behavior for any type of collections Maintains the logical size Copies elements during instantiation Provides default implementations of the +, ==, and str operations

Concrete Class

Inherits some data and methods and defines other data and methods, this class is instantiated

13.27 Give an example to show why interfaces are preferred over abstract classes.

Interfaces are preferred over abstract classes because an interface can define a common supertype for unrelated classes and is more flexible. EX: An how to eat method defined as an abstract class method can only be applied to subclasses that are animals, excluding all other non-animal edibles. An Edible interface however, can be impletmented by any class, animal, mineral, vegetable, fruit etc.

13.13 Suppose A is an interface. Can you create an instance using new A()?

No. Interfaces are abstract.

13.14 Suppose A is an interface. Can you declare a reference variable x with type A like this? A x;

No. Interfaces are abstract.

13.9 Can you create a Calendar object using the Calendar class?

No. The Calendar class is an abstract class.

13.22 Can you invoke the clone() method to clone an object if the class for the object does not implement the java.lang.Cloneable? Does the Date class implement Cloneable?

No. Yes.

Interface Polymorphism

Same operations, but different implementations of the data structures beneath the hood. Ex. add in ArrayBag vs LinkedBag

13.28 Define the terms abstract classes and interfaces. What are the similarities and differences between abstract classes and interfaces?

See the definitions above.

13.31 Why is the following code wrong? Rational r1 = new Rational(-2, 6); Object r2 = new Rational(1, 45); System.out.println(r2.compareTo(r1));

The Object type r2 does not have the compareTo method.

13.21 What is wrong in the following code? public class Test { public static void main(String[] args) { Person[] persons = {new Person(3), new Person(4), new Person(1)}; java.util.Arrays.sort(persons); } } class Person { private int id; Person(int id) { this.id = id; } }

The Person class does not implement the Comparable interface, two persons can not be compared using the compareTo method. (java.util.Arrays.sort() uses the compareTo method to sort arrays).

13.2 The getArea() and getPerimeter() methods may be removed from the GeometricObject class. What are the benefits of defining getArea() and getPerimeter() as abstract methods in the GeometricObject class?

The benefits are for generic programming. A variable of GeometricObject type can use the getArea and getPerimeter methods at compilation time.

13.32 Why is the following code wrong? Object r1 = new Rational(-2, 6); Rational r2 = new Rational(1, 45); System.out.println(r2.compareTo(r1));

The compareTo(Rational) method requires a Rational type object in the parameter in the Rational class.

13.8 What is wrong in the following code? public class Test { public static void main(String[] args) { Number x = new Integer(3); System.out.println(x.intValue()); System.out.println((Integer)x.compareTo(new Integer(4))); } }

The program has a syntax error because the member access operator (.) is executed before the casting operator.

13.7 What is wrong in the following code? (Note that the compareTo method for the Integer and Double classes was introduced in Section 10.7.) public class Test { public static void main(String[] args) { Number x = new Integer(3); System.out.println(x.intValue()); System.out.println(x.compareTo(new Integer(4))); } }

The program has a syntax error because x does not have the compareTo method.

Interface inheritance

The relationship between the class and the interface.

Rational Class

This class is for representing and processing rational numbers ( numerator / denominator) as JAVA does not have a data type that represents rational numbers and double/float are not precise. @the rational number is encapsulated in a rational object @immutable

13.17 True or false? If a class implements Comparable, the object of the class can invoke the compareTo method.

True.

Leverage Abstraction

Try to use just method calls in your code; avoid direct references to instance variables as much as possible. __str__, __add__, __eq__, and isEmpty just call other methods in an interface to get their work done

13.11 How do you create a Calendar object for the current time?

Use the GregorianCalendar class's constructor, you can create an instance of Calendar.

isEmpty, count, __len__, __str__, __add__, __eq__

Which methods have the same implementation in all collections?

Differing methods in Bag Classes

__contains__, add (between ArraySortedBag and other bags), __add__ (creates different types of bags)

Redundant methods in Bag Classes

__init__, isEmpty, __len__, __str__, __iter__, clear, and remove

deep copy

a full copy that creates all new field objects.

13.29 True or false? a. An interface is compiled into a separate bytecode file. b. An interface can have static methods. c. An interface can extend one or more interfaces. d. An interface can extend an abstract class. e. An abstract class can extend an interface.

a. True. b. False. c. True. d. False. e. True.

13.3 True or false? a. An abstract class can be used just like a nonabstract class except that you cannot use the new operator to create an instance from the abstract class. b. An abstract class can be extended. c. A subclass of a nonabstract superclass cannot be abstract. d. A subclass cannot override a concrete method in a superclass to define it as abstract. e. An abstract method must be nonstatic.

a. true. b. true. c. false. d. false. e. true.

13.1 Which of the following classes defines a legal abstract class? (a) class A { abstract void unfinished() { } } (b) public class abstract A { abstract void unfinished(); } (c) public class abstract A { abstract void unfinished(); } (d) abstract class A { protected void unfinished(); } (e) abstract class A { abstract void unfinished(); } (f) abstract class A { abstract int unfinished(); }

a.no: abstract method requires abstract class b. no: abstract keyword is in the wrong place c. no: abstract keyword is in the wrong place d. technically, can have an abstract class with out abstract method, unsure if protected counts. answer key just says no. e. yes. f. yes.

Marker Interface

an empty Interface that does not contain constants or methods

13.12 For a Calendar object c, how do you get its year, month, date, hour, minute, and second?

c.get(Calendar.YEAR) c.get(Calendar.MONTH) c.get(Calendar.DAY_ON_MONTH) c.get(Calendar.HOUR) c.get(Calendar.MINUTE) c.get(Calendar.SECOND)

13.15 Which of the following is a correct interface? (a) interface A { void print() { } } (b) abstract interface A extends I1, I2 { abstract void print() { } } (c) abstract interface A { print(); } (d) interface A { void print(); } (e) interface A { default void print() { } } (f) interface A { static int get() { return 0; } }

d

Show the output of the following code. public class Test { public static void main(String[] args) { House house1 = new House(1, 1750, 50); House house2 = (House)house1.clone(); System.out.println(house1.equals(house2); } }

false

13.23 Listing 13.5 has an error. If you add list.add(new BigInteger("3432323234344343102")); in line 11, you will see that the result is incorrect. This is due to the fact that a double value can have up to 17 significant digits. When invoking doubleValue() on a BigInteger object in line 24, precision is lost. Please fix the error by converting the numbers into BigDecimal and compare them using the compareTo method in line 24.

if (new BigDecimal(number + "").compareTo (new BigDecimal(list.get(i) + "")) < 0) {

Pythons object class

implements a default __eq__ and __str__

native keyword

indicates that a method is not written in java but is implemented in the JVM for the native platform

Abstract Method

methods that cannot be implemented in their own class because their implementation depends on a specific type of object owned by a subclass. @denoted by the abstract keyword in the method header ex: public abstract double getArea(); @UML denoted by italicizing the name of the class and the specific abstract method @abstract method cannot exist in a non abstract class, therefore all subclasses must override any abstract methods of the abstract superclass or are themselves abstract

13.19 Can the following code be compiled? Why? Integer n1 = new Integer(3); Object n2 = new Integer(4); System.out.println(n1.compareTo(n2));

n1 is an Integer object whose compareTo method require an Integer argument, but n2 is declared as Object. The compiler will raise an error.

13.5 Why do the following two lines of code compile but cause a runtime error? Number[] numberArray = new Integer[2]; numberArray[0] = new Double(1.5);

numberArray[0] is of the Integer type. It will be a casting error at runtime.

13.35 The preceding question shows a bug in the toString method. Revise the toString() method to fix the error.

public String toString() { if (numerator == 0 || denominator == 1) return numerator + ""; else return numerator + "/" + denominator; }

13.18 Which of the following is the correct method header for the compareTo method in the String class? public int compareTo(String o) public int compareTo(Object o)

public int compareTo(String o)

13.10 Which method in the Calendar class is abstract?

public void abstract add(int field, int amount) {}

13.33 How do you simplify the code in lines 82-85 in Listing 13.13 Rational.java using one line of code without using the if statement?

return (this.subtract((Rational)(other))).getNumerator() == 0;

13.22 Simplify the code in lines 10-15 in Listing 13.9 using one line of code. Show Answer

return getArea() > o.getArea() ? 1 : (getArea() < o.getArea() ? -1 : 0);

13.24 Show the output of the following code:

true false true

subinterface

when an interface extends another interface allowing it to inherit other interfaces. @The class that implements a subinterface must implement the abstract methods within all of the interfaces until reaching the superinterface.

shallow copy

when an object is copies, if a field houses an object, only the reference to the object is copied. a new object for the field is not created.


Ensembles d'études connexes

The US to 1877 (HIST1377) CH2 LS *Transplantation and borderlands*

View Set

CHAPTER 5 - DEVELOPMENT OF TEETH

View Set

Chapter 16 - Therapy & Treatment

View Set

MediaLab ASCP BoC Practice Exam - Fall 2022

View Set

ATI RN Fundamentals Online Practice 2023 B

View Set

Macroeconomics Chapter 7 Terms and Questions

View Set