Chapter 11 - JAVA PROGRAMMING Inheritance and Polymorphism

अब Quizwiz के साथ अपने होमवर्क और परीक्षाओं को एस करें!

11.30 How do you do the following? a. Create an ArrayList for storing double values? b. Append an object to a list? c. Insert an object at the beginning of a list? d. Find the number of objects in a list? e. Remove a given object from a list? f. Remove the last object from the list? g. Check whether a given object is in a list? h. Retrieve an object at a specified index from a list?

(a) ArrayList<Double> list = new ArrayList<Double>(); (b) list.add(object); (c) list.add(0, object); (d) list.size(); (e) list.remove(object); (f) list.remove(list.size() - 1); (g) list.contains(object); (h) list.get(index);

subtype

A type defined by a subclass.

Polymorphism

Allows a variable of a supertype to refer to a subtype object. (ig An object of a subclass can be used where ever its superclass object is used.)

child class / extended class / derived class

The class that inherits accessible data fields and methods from a superclass and may add new specialized data fields and methods and/or override superclass ones.

11.2 What keyword do you use to define a subclass?

The extends keyword is used to define a subclass that extends a superclass.

super.method(parameters);

This is used to reference a method in a superclass. Usually these are inherited so this is not always necessary unless....

final keyword for classes and methods

This prevents the class, method or variable from being extended or overridden or changed.

11.34 Explain why the following code is wrong. ArrayList<Double> list = new ArrayList<>(); list.add(1);

list consists of Double objects. list.add(1) automatically converts 1 into an Integer object. It will work if you change it to list.add(1.0).

default accessibility modifier

members can be accessed by same class and from the same package, but no where else @default designation

public keyword

members can be accessed from other classes, packages, subclasses @Intended for users of the class. @accessibility modifier cannot be changed on override.

protected keyword

members can only be accessed by the same class, subclasses, and classes in the same package. @intended for use in extended subclasses, not for users of the class @a subclass can override a protected method and change its visibility to public

private keyword

members can only be accessed from inside the class @Not intended for use outside the class @Cannot be overriden

visibility /accessibility modifiers

private, default, protected, public

11.5 How does a subclass invoke its superclass's constructor?

A subclass can explicitly invoke a suplerclass's constructor using the super keyword.

super

Keyword refers to the superclass and can be used to invoke the superclass's methods and constructors. This is used in two way: @To call a superclass constructor @To call a superclass method

11.13 If a method in a subclass has the same signature as a method in its superclass with the same return type, is the method overridden or overloaded?

Overriden.

Overriding a method

Overriding a method is recreating a method from a superclass in the subclass with the same signature and return type to specialize it for the subclass. @Must be prefaced with @Override key word. @Must have the same signature @Must have the same return type @Must be accessible by the subclass @Cannot be a static method

11.17 What is polymorphism? What is dynamic binding?

Polymorphism means that a variable of a supertype can refer to a subtype object. A method may be implemented in several classes along the inheritance chain. The JVM decides which method is invoked at runtime. This is known as dynamic binding.

11.38 What modifier should you use so that a class in a different package cannot access the class, but its subclasses in any package can access it?

Protected

11.41 How do you prevent a class from being extended? How do you prevent a method from being overridden?

Set the Class or method to accessibility final.

Explicit Casting

Similar to casting among primitive types. Allows a subclass to cast it's type to the superclass. EX: Student s = (student) o;

11.3 What is single inheritance? What is multiple inheritance? Does Java support multiple inheritance?

Single inheritance allows a subclass to extend only one superclass. Multiple inheritance allows a subclass to extend multiple classes. Java does not allow multiple inheritance

Multiple Inheritance

The ability to derive a subclass from multiple classes. Java does not allow this, however does allow a superclass and an interface.

Actual Type

The actual class for the object referenced by the variable.

superclass / parent class / base class

The class a subclass inherits from.

11.11 Identify the problems in the following code: 1 public class Circle { 2 private double radius; 3 4 public Circle(double radius) { 5 radius = radius; 6 } 7 8 public double getRadius() { 9 return radius; 10 } 11 12 public double getArea() { 13 return radius * radius * Math.PI; 14 } 15 } 16 17 class B extends Circle { 18 private double length; 19 20 B(double radius, double length) { 21 Circle(radius); 22 length = length; 23 } 24 25 @Override 26 public double getArea() { 27 return getArea() * length; 28 } 29 }

The following lines are erroneous: { radius = radius; // Must use this.radius = radius } class B extends Circle { Circle(radius); // Must use super(radius) length = length; // Must use this.length = length } public double getArea() { return getArea() * length; // super.getArea() }

11.29 When overriding the equals method, a common mistake is mistyping its signature in the subclass. For example, the equals method is incorrectly written as equals(Circle circle), as shown in (a) in following the code; instead, it should be equals(Object circle), as shown in (b). Show the output of running class Test with the Circle class in (a) and in (b), respectively. public class Test { public static void main(String[] args) { Object circle1 = new Circle(); Object circle2 = new Circle(); System.out.println(circle1.equals(circle2)); } } (a) class Circle { double radius; public boolean equals(Circle circle) { return this.radius == circle.radius; } } (b) class Circle { double radius; public boolean equals(Object o) { return this.radius == ((Circle)o).radius; } } If Object is replaced by Circle in the Test class, what would be the output to run Test using the Circle class in (a) and (b), respectively? Suppose that circle1.equals(circle2) is replaced by circle1.equals("Binding"), what would happen to run Test using the Circle class in (a) and (b), respectively? Reimplement the equals method in (b) to avoid a runtime error when comparing circle with a non-circle object.

The output is false if the Circle class in (a) is used. The Circle class has two overloaded methods: equals(Circle circle) defined in the Circle class and equals(Object o) defined in the Object class, inherited by the Circle class. At compile time, circle1.equals(circle2) is matched to equals(Object o), because the declared type for circle1 and circle2 is Object. (Note that either the declared type for circle1 and circle2 is Object would cause circle1.equals(circle2) to match circle1.equals(Object circle) by the compiler. The output is true if the Circle class in (b) is used. The Circle class overrides the equals(Object o) method defined in the Object class. At compile time, circle1.equals(circle2) is matched to equals(Object o) and at runtime the equals(Object o) method implemented in the Circle class is invoked. In (a), method equals(Object o) is used at both compile time and run time. circle1 and circle2 have different addresses, leading to "false" output. Method overriding follows dynamic binding (determined by the actual type), but method overloading is always determined by the declared type. What would be the output if Object is replaced by Circle in the Test class using the Circle class in (a) and (b), respectively? The output would be true for (a), because circle1.equals(circle2) matches circle1.equals(Circle object) exactly in this case. The output would be true for (b) because equals(Object c) is overridden in the Circle class. With circle1.equals(circle2) replaced by circle1.equals("Binding") and using the the Circle class in (a), the equals method in the Object class is used,circle1.equals(circle2) returns false. With circle1.equals(circle2) replaced by circle1.equals("Binding") and using the the Circle class in (b), the equals method in the Circle class is used,since it casts string "Binding" to Circle, it throws a casting exception. (b) should be reimplemented as follows to to avoid a runtime error when comparing circle with a non-circle object. class Circle { double radius; public boolean equals(Object o) { if (o instanceof Circle) return this.radius == ((Circle)o).radius; else return false; } }

Overloading a method

This means defining multiple methods with the same name, but different signatures. It is a new implementation for a method in the subclass. @Can be either in the same class or different classes related by inheritance @Have the same name, but different parameters as the other method.

11.9 How do you explicitly invoke a superclass's constructor from a subclass?

Use super() or super(args). This statement must be the first in the constructor in the subclass.

11.10 How do you invoke an overridden superclass method from a subclass?

Use super.method() or super.method(args).

Implicit Casting

When a superclass variable wants to be typed as a subclass reference with out explicitly being called. Ex. Object o = New Student(); Object is a superclass of Student. @This only works from super to sub, not the other

downcasting

When casting an instance of a superclass to a variable of its subclass requires explicit casting. Otherwise the complier could give a ClassCastException. @To validate this one can create an if (superclass variable instanceof subclassvariable);

constructor chaining

When constructing an object of a subclass, the subclass constructor first invokes its superclass constructor before performing its own tasks. If the superclass is a subclass, the superclass constructor invokes it's parent-class constructor before performing its own tasks; this continues until the ultimate parent class.

Casting Object

When one object reference is typecast into another object reference.

11.28 Does every object have a toString method and an equals method? Where do they come from? How are they used? Is it appropriate to override these methods?

Yes, because these two methods are defined in the Object class; therefore, they are available to all Java classes. The subclasses usually override these methods to provide specific information for these methods. The toString() method returns a string representation of the object; the equals() method compares the contents of two objects to determine whether they are the same.

11.25 For the GeometricObject and Circle classes in Listings 11.1 and 11.2, answer the following questions: a. Assume are circle and object1 created as follows: Circle circle = new Circle(1); GeometricObject object1 = new GeometricObject(); Are the following Boolean expressions true or false? (circle instanceof GeometricObject) (object instanceof GeometricObject) (circle instanceof Circle) (object instanceof Circle) b. Can the following statements be compiled? Circle circle = new Circle(5); GeometricObject object = circle; c. Can the following statements be compiled? GeometricObject object = new GeometricObject(); Circle circle = (Circle)object;

a) (circle instanceof GeometricObject1) => true (object instanceof GeometricObject1) => true (circle instanceof Circle1) => true (object instanceof Circle1) => false (b) Yes, because you can always cast from subclass to superclass. (c) Causing a runtime exception (ClassCastExcpetion)

11.4 What is the output of running the class C in (a)? What problem arises in compiling the program in (b)? (a) class A { public A() { System.out.println("A's no-arg constructor is invoked"); } } class B extends A { } public class C { public static void main(String[] args) { B b = new B(); } } (b) class A { public A(int x) { } } (c) class B extends A { public B() { } } public class C { public static void main(String[] args) { B b = new B(); } }

a. A's no-arg constructor is invoked b. The default constructor of B attempts to invoke the default of constructor of A, but class A's default constructor is not defined.

11.26 Suppose that Fruit, Apple, Orange, GoldenDelicious, and McIntosh are defined in the following inheritance hierarchy: Assume that the following code is given: Fruit fruit = new GoldenDelicious(); Orange orange = new Orange(); Answer the following questions: a. Is fruit instanceof Fruit? b. Is fruit instanceof Orange? 11.26c. Is fruit instanceof Apple? d. Is fruit instanceof GoldenDelicious? e. Is fruit instanceof McIntosh? f. Is orange instanceof Orange? g. Is orange instanceof Fruit? h. Is orange instanceof Apple? i. Suppose the method makeAppleCider is defined in the Apple class. Can fruit invoke this method? Can orange invoke this method? j. Suppose the method makeOrangeJuice is defined in the Orange class. Can orange invoke this method? Can fruit invoke this method? k. Is the statement Orange p = new Apple() legal? l. Is the statement McIntosh p = new Apple() legal? m. Is the statement Apple p = new McIntosh() legal?

a. Is fruit instanceof Fruit true? true b. Is fruit instanceof Orange true? false c. Is fruit instanceof Apple true? true d. Is fruit instanceof GoldDelicious true? true, because new GoldenDelicious() is assigned to fruit. The actual type for fruit at runtime is GoldenDelious. e. Is fruit instanceof Macintosh true? false f. Is orange instanceof Orange true? true g. Is orange instanceof Fruit true? true h. Is orange instanceof Apple true? false i. Suppose the method makeApple is defined in the Apple class. Can fruit invoke this method? No. It will give a compile error. However, you can invoke it using ((Apple)fruit).makeAppleCider(). Can orange invoke this method? No j. Suppose the method makeOrangeJuice is defined in the Orange class. Can orange invoke this method? Yes. Can fruit invoke this method? No. k. Is the statement Orange p = new Apple() legal? No l. Is the statement Macintosh p = new Apple() legal? No m. Is the statement Apple p = new Macintosh() legal? Yes

11.21 Show the output of the following code: (a) public class Test { public static void main(String[] args) { new Person().printPerson(); new Student().printPerson(); } } class Student extends Person { @Override public String getInfo() { return "Student"; } } class Person { public String getInfo() { return "Person"; } public void printPerson() { System.out.println(getInfo()); } } (b) public class Test { public static void main(String[] args) { new Person().printPerson(); new Student().printPerson(); } } class Student extends Person { private String getInfo() { return "Student"; } } class Person { private String getInfo() { return "Person"; } public void printPerson() { System.out.println(getInfo()); } }

a. Person Student b. Person Person For (a), new Person().printPerson() invokes the printPerson() method definedin the Person class, which then invokes the getInfo() method in the Person class.new Student().printPerson() invokes the printPerson() method definedin the Person class, which then invokes the getInfo() method in the Student class, because the calling object is a Student. For (b), new Student().printPerson() invokes the printPerson() method definedin the Person class, which then invokes the getInfo() method in the Person class. It does not invoke the getInfo() method in the Student class, because it is private and can only be invoked from a method in the Student class. Note that the getInfo() method is not overridden because it is private. You can only override a non-private method such as getInfo() in (a).

11.39 In the following code, the classes A and B are in the same package. If the question marks in (a) are replaced by blanks, can class B be compiled? If the question marks are replaced by private, can class B be compiled? If the question marks are replaced by protected, can class B be compiled? (a) package p1; public class A { ? int i; ? void m() { ... } } (b) package p1; public class B extends A { public void m1(String[] args) { System.out.println(i); m(); } }

a. yes because subclasses can access default methods and variables b. no because if i is private, it cannot be accessed by the subclass. c. yes because subclasses can access protected variables and methods.

public class XYZ extends XYZparent

extends is what tells the compiler this class XYZ is extending the superclass XYZparent

11.23 Show the output of following program: public class Test { public static void main(String[] args) { new A(); new B(); } } class A { int i = 7; public A() { setI(20); System.out.println("i from A is " + i); } public void setI(int i) { this.i = 2 * i; } } class B extends A { public B() { System.out.println("i from B is " + i); } public void setI(int i) { this.i = 3 * i; } }

i from A is 40 i from A is 60 i from B is 60

instanceof

keyword that determines if a superclass variable declared type matches the subclassvariable.

11.33 Explain why the following code displays [1, 3] rather than [2, 3]. ArrayList<Integer> list = new ArrayList<>(); list.add(1); list.add(2); list.add(3); list.remove(1); System.out.println(list); How do you remove integer value 3 from the list?

list.remove(1) sees this as the index, not the object. so it removes the element at location 1. To remove integer value 3, use list.remove("3");

11.19 Can you assign new int[50], new Integer[50], new String[50], or new Object[50], into a variable of Object[] type?

new int[50] cannot be assigned to into a variable of Object[] type, but new Integer[50], new String[50], or new Object[50] are fine.

11.40 In the following code, the classes A and B are in different packages. If the question marks in (a) are replaced by blanks, can class B be compiled? If the question marks are replaced by private, can class B be compiled? If the question marks are replaced by protected, can class B be compiled? (a) package p1; public class A { ? int i; ? void m() { ... } } (b) package p2; public class B extends A { public void m1(String[] args) { System.out.println(i); m(); } }

a. No. Default accessibility does not extend to subclasses in a different package. b. No. Private accessibility does not extend to subclasses in a different package. c. Yes. Protected accessibility does extent to sublclasses in a different package.

11.42 Indicate true or false for the following statements: a. A protected datum or method can be accessed by any class in the same package. b. A protected datum or method can be accessed by any class in different packages. c. A protected datum or method can be accessed by its subclasses in any package. d. A final class can have instances. e. A final class can be extended. f. A final method can be overridden.

a. True. b. False, only subclasses that extend the class in different packages. c. True. d. True. e. False. f. False.

11.24 Indicate true or false for the following statements: (a) You can always successfully cast an instance of a subclass to a superclass. (b) You can always successfully cast an instance of a superclass to a subclass.

(a) True. You can always successfully cast an instance of a subclass to a superclass. for example, casting apple to fruit is fine. (b) False. You cannot always successfully cast an instance of a superclass to a subclass. For example, casting fruit to apple is not always succeful unless a fruit is an apple.

Override annotation

@Override before a method in the subclass that is an override.

Single inheritance

A JAVA class may inherit directly from only one superclass.

supertype

A class defines a type. A type defined by a superclass is a supertype.

Dynamic Binding

A method can be implemented in several classes along the inheritance chain. The JVM decides which method is invoked at runtime.

Declared Type

A variable must be declared a type. A variable of a reference type can hold a null value or a reference to an instance of the declared type. The instance may be created using the constructor of the declared type OR ITS SUBTYPE. Determines which method to match at compile time.

11.32 Suppose the ArrayList list contains {"Dallas", "Dallas", "Houston", "Dallas"}. What is the list after invoking list.remove("Dallas") one time? Does the following code correctly remove all elements with value "Dallas" from the list? If not, correct the code. for (int i = 0; i < list.size(); i++) list.remove("Dallas");

After list.remove("Dallas"), the list becomes {"Dallas", "Houston", "Dallas"}. No. Here is the reason: Suppose the list contains two string elements "red" and "red". You want to remove "red" from the list. After the first "red" is removed, i becomes 1 and the list becomes {"red"}. i < list.size() is false. So the loop ends. The correct code should be : for (int i = 0; i < list.size(); i++) { if (list.remove(element)) i--; }

Inheritance

Allows one to define a general class (ie superclass) and later extend it to more specialized classes (ie subclasses) that inherits the properties and methods from the general class. @subclasses generally have more methods than superclass @Private data fields in the superclass are not accessible by a subclass, only by getters and setters @A subclass and superclass must have the same properties in an "is-a" @Not all "is-a" relationships are appropriate for inheritance. EX 1: A square is a rectangle, but should not extend from the rectangle class, rather should extend from geometricObject EX 2: Both people and trees have height and weight, but their classes should not be extensions. @Java only allows SINGLE INHERITANCE from a single superclass, however can be achieved using interfaces (abstract class)

11.22 public class Test { 2 public static void main(String[] args) { 3 A a = new A(3); 4 } 5 } 6 7 class A extends B { 8 public A(int t) { 9 System.out.println("A's constructor is invoked"); 10 } 11 } 12 13 class B { 14 public B() { 15 System.out.println("B's constructor is invoked"); 16 } 17 } Is the no-arg constructor of Object invoked when new A(3) is invoked?

B's constructor is invoked A's constructor is invoked The default constructor of Object is invoked, when new A(3) is invoked. The Object's constructor is invoked before any statements in B's constructor are executed.

upcasting

Casting an instance of a subclass to a variable of a superclass @An instance of a subclass is ALWAYS an instance of a superclass, so can be implicit or explicit.

11.36 Correct errors in the following statements: int[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5}; System.out.println(java.util.Collections.max(array));

Collections only works on ArrayList objects, not on primitive array.

super()

Constructors of the superclass are not inherited, they can only be invoked from the constructors of the subclasses by using super(). @ super() or super(args) must be the FIRST statement of the subclasses constructor.

11.37 What modifier should you use on a class so that a class in the same package can access it, but a class in a different package cannot access it?

Default.

What are the three pillars of object oriented programming?

Encapsulation Inheritance Polymorphism

11.31 Identify the errors in the following code. ArrayList<String> list = new ArrayList<>(); list.add("Denver"); list.add("Austin"); list.add(new java.util.Date()); String city = list.get(0); list.set(3, "Dallas"); System.out.println(list.get(3));

Error 1: list.add(new java.util.Date()); is wrong, because it is an array list of strings. You cannot add Date objects to this list. Error 2: list.set(3, "Dallas"); is wrong because there is no element at index 3 in the list. Error 3: list.get(3) is wrong because there is no element at index 3 in the list.

11.1 True or false? A subclass is a subset of a superclass.

False. A subclass is an extension of a superclass and normally contains more details information than its superclass.

11.6 True or false? When invoking a constructor from a subclass, its superclass's no-arg constructor is always invoked.

False. If a subclass's constructor explicitly invoke a superclass's constructor, the superclass's no-arg constructor is not invoked.

11.7 True or false? You can override a private method defined in a superclass.

False. You can only override accessible instance methods.

11.8 True or false? You can override a static method defined in a superclass.

False. You can only override accessible instance methods.

11.35 Correct errors in the following statements: int[] array = {3, 5, 95, 4, 15, 34, 3, 6, 5}; ArrayList<Integer> list = new ArrayList<>(Arrays.asList(array));

Int is a primitive. The correct way is to wrap int to Integer first, and then apply the integer objects to the ArrayList. To use asList(array), array must be an array of objects.

11.16 What is the benefit of using the @Override annotation?

It forces the compiler to check the signature of the overridden method to ensure that the method is defined correctly.

11.14 If a method in a subclass has the same signature as a method in its superclass with a different return type, will this be a problem?

It will be a syntax error.

11.20 What is wrong in the following code? 1 public class Test { 2 public static void main(String[] args) { 3 Integer[] list1 = {12, 24, 55, 1}; 4 Double[] list2 = {12.4, 24.0, 55.2, 1.0}; 5 int[] list3 = {1, 2, 3}; 6 printArray(list1); 7 printArray(list2); 8 printArray(list3); 9 } 10 11 public static void printArray(Object[] list) { 12 for (Object o: list) 13 System.out.print(o + " "); 14 System.out.println(); 15 } 16 }

Line 8 causes a compile error, because int[] cannot be passed to Object[]. Int is a primitive and must be wrapped before it can be used as an Object.

11.18 Describe the difference between method matching and method binding.

Matching a method signature and binding a method implementation are two separate issues. The declared type of the reference variable decides which method to match at compile time. The compiler finds a matching method according to parameter type, number of parameters, and order of the parameters at compile time. A method may be implemented in several subclasses. The JVM dynamically binds the implementation of the method at runtime, decided by the actual class of the object referenced by the variable.

11.12 Explain the difference between method overloading and method overriding.

Method overloading defines methods of the same name in a class. Method overriding modifies the methods that are defined in the superclasses.

Does casting an object reference generate a new object ?

No. Both variables now reference the same object.

11.27 What is wrong in the following code? 1 public class Test { 2 public static void main(String[] args) { 3 Object fruit = new Fruit(); 4 Object apple = (Apple)fruit; 5 } 6 } 7 8 class Apple extends Fruit { 9 } 10 11 class Fruit { 12 }

Object apple = (Apple)fruit; Causes a runtime ClassCastingException.

What is the ultimate parent/super Class?

Object. Every class in JAVA is descended from java.lang.Object class. @If no superclass/inheritence is specified on class creation, Object is the default superclass.

11.15 If a method in a subclass has the same name as a method in its superclass with different parameter types, is the method overridden or overloaded?

Overloaded.


संबंधित स्टडी सेट्स

Chapter 14: Small Business Finance: Using Equity, Debt, and Gifts

View Set

35Qw/exp Module 8: HIV Infection & Aids

View Set

Introduction to Public Health Final Exam

View Set

Bless Me Ultima Review Questions

View Set

Select the word or phrase that doesn't belong.

View Set

Ch. 17 Go West Young Man! Westward Expansion, 1840-1900

View Set

CHE 3171 Exam 1 - SAChE1 Hazards and Risks - What Can Go Wrong?

View Set

Chapter 11: Consideration and a Promissionary Estoppel - DONE

View Set