Polymorphism in Java
Every object in Java knows its own class and can access this information through method . A. getClass. B. getInformation. C. objectClass. D. objectInformation.
A. getClass.
Polymorphism enables you to: A. program in the general. B. program in the specific. C. absorb attributes and behavior from previous classes. D. hide information from the user.
A. program in the general.
Can we inherit code from more than one superclass?
no
The type of the _____, not the type of the reference, determines which version of a ____ is invoked.
object, method
A ____ reference can refer to different types of ____ over time.
polymorphic , objects
interface
special tool that allows you to represent a common supertype between classes without actually sharing code; consists of a set of method declarations without a method body
downcasting example
((car) v).methodOnCar();
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);
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.
Defining characteristics of an abstract class
* A class that contains abstract methods must be declared abstract. * An abstract class cannot be instantiated. * A class without any abstract methods can be declared abstract--this is done to prevent it from being instantiated. * Every concrete class that extends an abstract class must provide implementation for all abstract methods.
Queue Methods:
-Enqueue/Add -Dequeue/Remove -IsEmpty -IsFull
Class Variable
-One fixed memory location - Any object can change the value - Can be manipulated without creating instance of a class
The iterator class overloades the...
... ++ and - - and * (dereferencing) operators
Virtual functions allow...
... the most specific version of a member function in an inheritance hierarchy to be selected for execution
Polymorphism occurs when it takes the advantage of the fact that...
...a pointer to a derived class is type-compatible with a pointer to its base class
A Standard Template Library is...
...a set of C++ templates for useful algorithms and data structures
If a class has at least one pure virtual function it is considered...
...an abstract class
Abstract classes and pure virtual functions can be used to define...
...an interface that must be implemented by derived classes
Polymorphism refers to the ability to...
...associate many meanings to one function name by means of a special mechanism known as a virtual function
An abstract class is a class that...
...contains no objects that are not members of derived classes
Base class pointers can point to...
...derived class objects
A piece of code is said to be polymorphic if...
...executing the code with different types of data produces different behavior
Iterators provide...
...member functions begin() and end() that returns the beginning and the end of the container
The compareTo method should return ___ when equals would return true, a neg number when this < obj and a positive number when this> obj
0
What are the two basic rules for type compatibility of inheritance?
1) A derived class pointer can always be assigned to a base class pointer 2) A type cast is required to perform the opposite assignment of a base class pointer to a derived class pointer
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.
Virtual methods
A class can declare _____________ and properties
Several
A class can implement __________ interfaces
One
A class can only inherit ________ base class
supertype
A class defines a type. A type defined by a superclass is a supertype.
Child class
A class that extends the base class.
Abstract Class
A class that is used only as the superclass for other classes. You cannot create objects of an abstract class. Such a class must have the keyword "abstract" in its declaration.
What is a container?
A class that stores data and organizes the data
Sorted List
A data collection that maintains its entries in sorted order and retrieves them by their position number within the list.
What is a Queue?
A datastructure of unordered items
Polymorphism
A feature of object-oriented programming whereby the correct version of a method is determined during program execution instead of during compilation.
Dynamic Binding
A method can be implemented in several classes along the inheritance chain. The JVM decides which method is invoked at runtime.
Virtual
A method is said to be a virtual when it is declared
Abstract Method
A method that has no body. The declaration of such a method must include the keyword abstract and end in a semicolon. The class of an abstract method must be abstract.
Super
A reference to the parent. In a method definition, this refers to the the parent
inheritance
A subclass can use iVars, and methods from superclass
polymorphism
A subclass overriding the methods of a superclass is an example of ...
subtype
A type defined by a subclass.
Polymorphic Variable
A variable having a dynamic type.
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.
What is an example of an STL?
A vector
Inheritance
A way of building new classes bases on existing ones: creates an "is-a" relationship.
Abstract
Abstract classes are special classes defined with the keyword __________
Abstract/virtual
Abstract operations are declared as
How do we fix the dreaded diamond/multiple inheritance problem of implementation of the same methods in the classes a subclass is multiply inheriting from?
Abstraction - make the conflicting methods in the parent classes that are multiply inherited from abstract; Interfaces in Java
Default Access Modifier
Accessible only within package
Protected access modifier
Accessible within package and outside the package but through inheritance only
Child class
Add new fields and methods
Subclasses
Additional data members
Subclasses
Additional methods
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--; }
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.)
Polymorphism
Allows abstract operations to be defined and used
Inheritance
Allows child classes to inherit the characteristics of an existing parent class.
Advantages of using dynamic polymorphism
Allows methods to be overriden - allows method to be called on actual type of an object if parent and child both have the same type and we are referring to the object via its parent type.
Interface
An ______________ can implement several interfaces
Difference between an abstract class and an interface
An abstract class can have 0 or more abstract methods as well as defined methods, an interface's methods are all abstract; an abstract class can have member state whereas an interface contains no state (apart from constants); a class can inherit from multiple interfaces but it can't inherit from multiple abstract classes.
If a base class pointer does not actually point to a derived class object, what may happen?
An error
How can polymorphism be accomplished using interfaces?
An interface name can be used as the type of a reference. Such as reference variable can refer to any object of any class that implements that interface. Because all classes implement the same interface, they have methods with common signatures, which can be dynamically bound.
What is an example of an abstract class?
Animal is an abstract class: there are no animals that are not Dogs, or cats, or lions, or tigers, or bears, oh my ......
Abstract Superclass
Another term for abstract class.
Abstract operations
Are defined in the base class and implemented in the child classes
Subclasses
Are more specific and have more functionality
Constructors
Are not inherited
In static polymorphism, when is the decision made about which method (which exists both in parent & child class) to execute for an object that we refer to via its parent type? (i.e. by casting to parent type)
At compile time
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.
static
Both Abstract and Interface may have ___________ variables
Class
Can be used through its parent interface
Child class
Can extend the parent class
Class
Can implement an interface by providing implementation for all its methods.
Structures
Cannot be inherited
Java Interface
Cannot contain an implementation of the methods, only the signature (name, parameters and exceptions) of the method.
Disadvantages of using static polymorphism for methods
Cannot override methods - the parent method will be run
Polymorphism
Capability of changing into many forms. It's a feature that allows one method to behave in different ways depending on various factors. Can be implemented through overloading and overriding.
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.
Syntax
Class class_name implements interface_name
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.
In static polymorphism, what do type errors cause?
Compile errors
Static polymorphism involves making a choice between multiple implementations at?
Compile time
Non-Abstract Class
Concrete Class
Variables and collections
Consequently, we can define (such as arrays) that don't have to know in advance what kind of specific object they will hold, only that they'll hold objects that implement the interface
Class hierarchy
Consists of a superclass and its descendants.
What are the two important data structures in the STL?
Containers Iterators
try block
Contains program statements that we think can raise exceptions
RaceCar mcQueen = new RaceCar();
Create an instance of RaceCar without any parameters named mcQueen (would be in runner class)
Interfaces can have methods. A. 0 B. 1 C. 2 D. any number of
D. any number of
Static polymorphism
Decisions made at compile-time, since we don't know what the true type of an object will be (casted to parent type so can't tell actual sub-type) we run the parent method
String c = "cookie";
Declare a string named "c" that is for "cookie" --- That's good enough for me!
int a = 37;
Declare an integer named a with a value of 37.
New members
Declaring ____________ with the same name or signature hides the inherited ones
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.
Interface
Defined as a syntactical contract that all the classes inheriting the interface should follow
Override
Derived classes can __________ the implementation of these members
Polymorphism
Describes how objects in a hierarchy act according to what they are rather than what names they have
How do you indicate an interface in UML
Draw class diagram as normal, put <<interface>> before class name in top section of class diagram, have method names all abstract (in {} ).
Are all methods in Java dynamic polymorphic or static polymorphic?
Dynamic polymorphic
What are the three pillars of object oriented programming?
Encapsulation Inheritance Polymorphism
Encapsulation
Encapsulation in Java is a mechanism of wrapping the data (variables) and code acting on the data (methods) together as a single unit. In encapsulation, the variables of a class will be hidden from other classes.
Polymorphism
Ensures that the appropriate method of the subclass is called through its base class interface
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.
Public and abstract
Every method in an interface is ____ and ___.
Public, static, and final
Every variable in an interface is ____, _____, and ______.
Runtime
Exact method to be called is determined at _________, just before performing the call
Disadvantages of using dynamic polymorphism for methods
Expensive - checks types at runtime
Derived class
Extends its base class
Inheritance
Extensibility, reusability, provides abstraction, eliminates redundant code
True or false: an interface can inherit from more than one class?
False, another class can inherit from more than one interface
11.7 True or false? You can override a private method defined in a superclass.
False. You can only override accessible instance methods.
Overriding
Feature that allows a subclass or child class to provide a specific implementation of a method that is already provided by one of its super-classes or parent classes
Attributes
Fields and Properties
Generalization
General characteristics are specified high up in the hierarchy
Interface
Gives you the ability to specify set of behaviors that all classes that implement the interface will share in common
Interface
Group of variables and methods declarations.
Concrete class
Has implementation of all of its inherited members either from interface or abstract class
Composition
Has-a relationship
Subclasses
Have all of the data membets and methods of the superclass
Object
If a class is not declared to inherit from another then it implicitly inherits from the _______ class
super(name, weight);
If the animal class has the iVars String name and double weight how would you write the "super" line of code to include them in an inherited class Dog?
public Dog(String name, double weight)
If the animal class has the iVars String name and double weight how would you write the constructor of Dog to include name and weight ( { not necessary)
What is the problem with a dreaded diamond?
If the two middle classes independently override a method from its parent class (class at the top), the bottom class (which multiply inherits from the two middle classes) will not know which method to inherit
What problems can occur with multiple inheritance?
If two parent classes have implementations of the same method, which method should get inherited to be implemented?
Derived interface
Implements base interface
Class
Implements interface
Object
In C#, all classes are subclasses of the _____________ class
Multiple
In C#, there is no ________ inheritance
Constructor
In the ______________ of the derived class we use the keyword base to invoke the constructor of the base class
Base
In the constructor of the derived class we use the keyword ________ to invoke the constructor of the parent class
Extends
Indicates inheritance. Java classes can have only one parent.
____ can be applied to interfaces so that one interface can be derived from another.
Inheritance
Inheritance
Inheritance can be defined as the process where one class acquires the properties (methods and fields) of another.
Transitive relation
Inheritance is ______________
Derived class
Inherits base class/parent class
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.
What
Interface defines the ________ part of the syntactical contract
Late binding
Is slower than normal binding
Inheritance
Is-a relationship
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.
Constructor
It is called when an instance of object is created and memory is allocated for the object
Root
It is the __________ of the inheritance hierarchy in C#
super
It is used to invoke the superclass constructor from subclass.
In ad-hoc/sub-type polymorphism (an OOP-specific type of dynamic polymorphism), how does the compiler figure out to run the child method instead of the parent method for an object being accessed via its parent type?
It looks in memory whilst the program is running and finds the object is really of its child type (although being accessed via parent type), and if it finds parent and child implements a particular method, it will run the method in the child (since its figured out the object is actually of the child type not the parent type)
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.
super
Keyword is used to refer to member of base class from a sub class.
Inheritance
Leads to a hierarchy of classes and/or interfaces in an application
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.
Abstract classes
May not be instantiated, and require subclasses to provide implementations for the abstract methods.
Child class
May override some of the behaviors of the parent class
Exception handling
Mechanism to handle the runtime errors so that normal flow of the application can be maintained
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.
Virtual method
Method that can be used the same way on instances of base and derived classes but its implementation is different
Dynamic polymorphism
Method with implementation in child and parent is run in the child class, at run-time (so that we know the child's type)
Operations
Methods
Override
Methods that are declared as virtual in a base class can be overridden using the keyword __________ in the derived class
Interfaces are totally abstract, allow for ________ ___________ from them.
Multiple inheritance
Commas
Names of interfaces should be separated by ____.
Can you instantiate an object of an abstract class?
No
Do overridden static fields exhibit dynamic polymorphism?
No
Do overridden static methods exhibit dynamic polymorphism?
No - same implementation for all objects so why would it?
Can you override methods with static, private or final access modifiers?
No - static: all objects have same implementation, private: cannot access method from subclass, final: once method is implemented, cannot be changed
Does casting an object reference generate a new object ?
No. Both variables now reference the same object.
the _____ class is the superclass to all objects
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.
java classes are subclasses
Object class
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.
Instance Variable
Objects created from the same class have their own distinct copies of instance variables
Type compatibility
Objects of a derived class can be used whenever objects of a base class object are expected
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.
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.
Late method binding
Polymorphism is implemented using a technique called
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.
Multithreading
Process of executing two or more threads simultaneously
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
Child class
Redefine methods (modify existing behavior)
Abstraction
Refers to hiding some non-essential information and only showing parts of it
How does Java fix the problem of conflicting methods in multiple inheritance?
Restricts classes to only having at most one parent, unless the parent class is a a special type of class called an interface
In dynamic polymorphism, what do type errors cause?
Run-time faults (crashes)
Dynamic polymorphism involves making a choice between multiple implementations at?
Runtime
What are the 2 types of containers?
Sequential Associative
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.
How might you use static polymorphism when you have a bunch of shapes, each of which have their own draw() method?
Shape doesn't have a draw() method, only the child classes do. Keep a list of Shape references, figure out what each object really is (i.e. square, circle - what child class is it), narrow the reference (downcast to this child class type) and then call draw() on this narrowed reference.
How might you use dynamic polymorphism when you have a bunch of shapes, each of which have their own draw() method?
Shape has a draw() method as do the child classes. Keep a list of Shape references, let the compiler figure out what to do with each Shape reference by calling the draw method on it, figures out which child class it is (i.e. its a Circle object so run draw() in Circle)
Explicit Casting
Similar to casting among primitive types. Allows a subclass to cast it's type to the superclass. EX: Student s = (student) o;
Why are interfaces totally abstract?
So that if there are conflicting methods (same name, arguments, return type but different body), there is no implementation of these methods in parent classes (interfaces) so no conflict caused in subclass, these methods are then implemented in the subclass itself.
Inheritance
Software Reuse -Each class only has one super class - Child class can override parent methods
Abstract classes
Special classes defined with the keyword abstract
What is an interface?
Special classes that are entirely abstract (no state, all methods are abstract), the only classes in Java allowed to do multiple inheritance (i.e. allows classes to multiply inherit from it and more interfaces).
Specialization
Specific characteristics are specified below the hierarchy
Base class
Specify the name of the _________ after the name of the derived
Type of polymorphism with shadowing of fields?
Static polymorphism
What type of polymorphism do we have if we can get different method implementations by casting an object to different types?
Static polymorphism (casting to different types means different parents so different implementation of method from different parents as parent method run in static polymorphism)
Type of polymorphism in ML
Static polymorphism (decision made at compile-time, type errors give compile errors)
Differences between static and dynamic polymorphism (method run, when decision is made, result of type errors)
Static; Dynamic Run parent method; Run child method Decision made at compile; Decision made at run-time Type checked at compile-time, type of child checked at run-time Type errors cause compile errors; type errors cause run-time fault (crashes)
What does a sequential container do?
Stores items in the form of sequences
Superclass
Subclasses can add to the ________
Polymorphism
The ability to take more than one form
Actual Type
The actual class for the object referenced by the variable.
Base class
The class upon which a child class is defined and extended from
Why does abstraction fix the problem of one or more conflicting methods in multiple inheritance?
The conflicting methods have no implementation that can conflict, have the implementation in the child class that multiple inherits instead
Static Type
The data type in a variable's declaration. A static type is fixed and determined during compilation.
Dynamic Type
The data type of the object that a variable references at a point during program execution.
How
The deriving classes define the ________ part of the syntactical contract
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() }
Dynamic Binding/Late Binding
The mechanism used during program execution to determine which version of a method to call.
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.
final keyword for classes and methods
This prevents the class, method or variable from being extended or overridden or changed.
False
True or False: A class can only implement one interface.
True
True or False: Class makes use of an interface by implementing that interface by name.
Why is there a performance overhead with dynamic polymorphism?
Types are checked at run-time
super
Used by class constructors to invoke constructors of its parent class
Advantages of using static polymorphism for methods
Using it for methods that are upcasted will allow compile errors to be seen by being able to see if the object really is of the upcasted type and calling that method is valid on that type; can overload methods without extra cost of checking at runtime through dynamic polymorphism; types checked at compile time so less expensive
Constant
Variables in an interface should have ____ values.
What are the three types of sequential containers?
Vector List Deque
creating objects: , car is subclass of vehicle
Vehicle v = new Car();
What makes polymorphism possible?
Virtual functions
What problems are there with static polymorphism in OOP?
What if we want to add a new child class? Then we have to go through and add code to check if the object is of this type, and then downcast this object (referred to by its parent class before) to its child type and call the method on this downcasted object.
object
What is the cosmic superclass, included with every class you create.
2323
What is the output? Object x = new String("2323"); out.println(x.toString());
2
What is the output? class A { int i; void display() { System.out.println(i); } } class B extends A { int j; void display() { System.out.println(j); } } class inheritance_demo { public static void main(String args[]) { B obj = new B(); obj.i=1; obj.j=2; obj.display(); } }
2 2
What is the output? class A { public int i; private int j; } class B extends A { void display() { super.j = super.i + 1; System.out.println(super.i + " " + super.j); } } class inheritance { public static void main(String args[]) { B obj = new B(); obj.i=1; obj.j=2; obj.display(); } }
1 2
What is the output? class A { public int i; public int j; A() { i = 1; j = 2; } } class B extends A { int a; B() { super(); } } class super_use { public static void main(String args[]) { B obj = new B(); System.out.println(obj.i + " " + obj.j) } }
17
What is the output? class A{ private int x; public A() { x=17;} public String toString() { return ""+x; } } class B extends A{ } //test code in the main method A one = new A(); out.println(one);
17 17
What is the output? class A{ private int x; public A() { x=17;} public String toString() { return ""+x; } } class B extends A{ } //test code in the main method A one = new A(); out.println(one); one = new B(); out.println(one);
compiler error
What is the output? final class A{ private int x; public A() { x=17;} public String toString() { return ""+x; } } class B extends A{ } //test code in the main method A one = new A(); out.println(one);
What is the dreaded diamond?
When a base class has 2 children who are the parents of another class through multiple inheritance (the same class inherits from both), forming a diamond.
Define polymorphism
When a call to a member function will cause a different function to be executed depending on the type of object that invokes the function
Multilevel inheritance
When a class extends a class, which extends another class
Multiple inheritance
When a class extends a class, which extends another class.
Methods
When a class implements an interface, it implements all the _____ declared in that interface.
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);
Casting Object
When one object reference is typecast into another object reference.
Multiple inheritance
When we want a class to inherit from more than one parent class
Substitution Principle
Whenever a base class type is expected, a child (or descendant) will suffice.
public class RaceCar extends Car
Write the 1st line class declaration for RaceCar a Subclass of Car
Do overridden methods exhibit dynamic polymorphism?
Yes (providing non-static)
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.
abstract method
a header without an implementation; the actual body is not specified, to allow/force different classes to implement the behavior in its way
Describe a list
a sequence of items that allows quick additions and removals from any position
non abstract methods are inherited by
a subclass
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)
Which of the following statements is false? a. An advantage of inheritance over interfaces is that only inheritance provides the is-a relationship. b. Objects of any subclass of a class that implements an interface can also be thought of as objects of that interface type. c. When a method parameter is declared with a subclass or interface type, the method processes the object passed as an argument polymorphically. d. All objects have the methods of class Object.
a. An advantage of inheritance over interfaces is that only inheritance provides the is-a relationship.
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.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.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).
Polymorphism enables you to: a. program in the general. b. program in the specific. c. absorb attributes and behavior from previous classes. d. hide information from the user.
a. Program in the general
Which of the following statements is false? a. References to interface types do not have access to method toString. b. Method toString can be invoked implicitly on any object. c. With inheritance, classes and their inherited classes tend to be very similar. d. Dramatically different classes can often meaningfully implement the same interface.
a. References to interface types do not have access to method toString.
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.
All of the following methods are implicitly final except: a. a method in an abstract class. b. a private method. c. a method declared in a final class. d. static method.
a. a method in an abstract class.
Which of the following statements about abstract superclasses is true? a. abstract superclasses may contain data. b. abstract superclasses may not contain implementations of methods. c. abstract superclasses must declare all methods as abstract. d. abstract superclasses must declare all data members not given values as abstract.
a. abstract superclasses may contain data
Polymorphism allows for specifics to be dealt with during: a. execution. b. compilation. c. programming. d. debugging.
a. execution
Every object in Java knows its own class and can access this information through method . a. getClass. b. getInformation. c. objectClass. d. objectInformation.
a. getClass
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.
polymorphism
ability for the same code to be used with different types of objects and behave differently with each
public members
accessible to all classes
protected members
accessible within all classes in the same package and within subclasses in other packages
polymorphism
achieved by overriding methods
base class
aka superclass aka parent class the class from which the subclass is derived from
if a class implements an interface then ____ methods that appear in the interface _______ with the exact same header
all, must be implemented
how is multiple inheritance is supported through th use of interfaces
allows a class to have more than one super class to have more than one super class and to inherit features from all parent class
A derived class pointer can _________ be assigned to a base class pointer (always, never)
always
any methods that are abstract must be implemented by
an inheriting class
What is an iterator?
an object that behaves like a pointer and is used to access items stored in containers
an interface extends
another interface, rather than implementing
invoking methods
any method declared for type vehicle can be invoked on object v.
derived class
applies only to the immediate parent
Describe a vector
array style of storing items - automatically grows as needed and easy to insert at the end of array - not easy to insert in middle of array
Which of the following is not possible? a. A class that implements two interfaces. b. A class that inherits from two classes. c. A class that inherits from one class, and implements an interface. d. All of the above are possible.
b. a class that inherits from two classes.
Assigning a subclass reference to a superclass variable is safe ________. a. because the subclass object has an object of its superclass. b. because the subclass object is an object of its superclass. c. only when the superclass is abstract. d. only when the superclass is concrete.
b. because the subclass object is an object of its superclass
Which keyword is used to specify that a class will define the methods of an interface? a. uses b. implements c. defines d. extends
b. implements
If the superclass contains only abstract method declarations, the superclass is used for ________. a. implementation inheritance. b. interface inheritance. c. Both. d. Neither.
b. interface inheritance
It is a UML convention to denote the name of an abstract class in ________. a. bold. b. italics. c. a diamond. d. there is no convention of the UML to denote abstract classes—they are listed just as any other class.
b. italics
Which of the following is false? a. You should not call overridable methods from constructors—when creating a subclass object, this could lead to an overridden method being called before the subclass object is fully initialized. b. It's OK to any of a class's methods from its constructors. c. When you construct a subclass object, its constructor first calls one of the direct superclass's constructors. If the superclass constructor calls an overridable method, the subclass's version of that method will be called by the superclass constructor. d. It's acceptable to call a static method from a constructor.
b. its ok to any of a class' methods from its constructors.
For which of the following would polymorphism not provide a clean solution? a. A billing program where there is a variety of client types that are billed with different fee structures. b. A maintenance log program where data for a variety of types of machines is collected and maintenance schedules are produced for each machine based on the data collected. c. A program to compute a 5% savings account interest for a variety of clients. d. An IRS program that maintains information on a variety of taxpayers and determines who to audit based on criteria for classes of taxpayers.
c. A program to compute a 5% savings account interest for a variety of clients.
Which interface is specifically intended to be implemented by classes that can be used with the try-with-resources statement? a. Comparable b. Runnable c. AutoCloseable d. Serializable
c. AutoClosable
Which of the following statements is false? a. In Java SE 8, an interface may declare default methods—that is, public methods with concrete implementations that specify how an operation should be performed. b. When a class implements an interface, the class receives the interface's default concrete implementations if it does not override them. c. When you enhance an existing interface with default methods—any class that implemented the original interface will break. d. With default methods, you can declare common method implementations in interfaces (rather than abstract classes), which gives you more flexibility in designing your classes.
c. When you enhance an existing interface with default methods- any class that implemented the original interface will break.
A class that implements an interface but does not declare all of the interface's methods must be declared ________. a. public. b. interface. c. abstract. d. final.
c. abstract
A(n) class cannot be instantiated. a. final. b. concrete. c. abstract. d. polymorphic.
c. abstract
Classes and methods are declared final for all but the following reasons: a. final methods allow inlining the code. b. final methods and classes prevent further inheritance. c. final methods are static. d. final methods can improve performance.
c. final methods are static
The UML distinguishes an interface from other classes by placing the word "interface" in above the interface name. a. italics. b. carets. c. guillemets. d. bold.
c. guillemets ' '
Which of the following could be used to declare abstract method method1 in abstract class Class1 (method1 returns an int and takes no arguments)? a. public int method1(); b. public int abstract method1(); c. public abstract int method1(); d. public int nonfinal method1();
c. public abstract int method1();
In Java SE 7 and earlier, an interface may contain: a. private static data and public abstract methods. b. only public abstract methods. c. public static final data and public abstract methods. d. private static data and public final methods.
c. public static final data and abstract methods.
public class A extends B {
class A is a subclass of B
public class B extends A {
class B is a subclass of A
keyword abstract needs to be included in
class header, method headers for any methods that are abstract
An abstract class
class with both implemented and abstract methods. can have variables and constructors
Abstract Class
class with one or more abstract methods
Which benefits the class more: interfaces or clients?
clients
Non-abstract classes are called:
concrete
a subclass requires a ____ if the superclass has a constructor
constructor
everything except for _____ is inherited from the superclass including members that are not accessible in the subclass
constructors
Which of the following statements is false? a. As of Java SE 8, any interface containing only one method is known as a functional interface. b. There are many functional interfaces throughout the Java APIs. c. Functional interfaces are used extensively with Java SE 8's new lambda capabilities. d. Anonymous methods provide a shorthand notation for creating lambdas.
d. Anonymous methods provide a shorthand notation for creating lambdas.
Non-abstract classes are called ________. a. real classes. b. instance classes. c. implementable classes. d. concrete classes.
d. Concrete classes.
When a superclass variable refers to a subclass object and a method is called on that object, the proper implementation is determined at execution time. What is the process of determining the correct method to call? a. early binding. b. non-binding. c. on-time binding. d. late binding.
d. Late binding also called dynamic binding.
Which of the following statements is false? a. Prior to Java SE 8, it was common to associate with an interface a class containing static helper methods for working with objects that implemented the interface. b. Class Collections contains many static helper methods for working with objects that implement interfaces Collection, List, Set and more. c. Collections method sort can sort objects of any class that implements interface List. d. With non-static interface methods, helper methods can now be declared directly in interfaces rather than in separate classes.
d. With non-static interface methods, helper methods can now be declared directly in interfaces rather than in separate classes.
Which statement best describes the relationship between superclass and subclass types? a. A subclass reference cannot be assigned to a superclass variable and a superclass reference cannot be assigned to a subclass variable. b. A subclass reference can be assigned to a superclass variable and a superclass reference can be assigned to a subclass variable. c. A superclass reference can be assigned to a subclass variable, but a subclass reference cannot be assigned to a superclass variable. d. A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable.
d. a subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable.
Interfaces can have methods. a. 0 b. 1 c. 2 d. any number of
d. any number of methods
Consider the abstract superclass below: public abstract class Foo { private int a; public int b; public Foo(int aVal, int bVal) { a = aVal; b = bVal; } public abstract int calculate(); } Any concrete subclass that extends class Foo: a. Must implement a method called calculate. b. Will not be able to access the instance variable a. c. Neither (a) nor (b). d. Both (a) and (b).
d. both a and b
Which of the following does not complete the sentence correctly? An interface . a. forces classes that implement it to declare all the abstract interface methods. b. can be used in place of an abstract class when there is no default implementation to inherit. c. is declared in a file by itself and is saved in a file with the same name as the interface followed by the .java extension. d. can be instantiated.
d. can be instantiated
Declaring a method final means: a. it will prepare the object for garbage collection. b. it cannot be accessed from outside its class. c. it cannot be overloaded. d. it cannot be overridden.
d. it cannot be overriden
Consider classes A, B and C, where A is an abstract superclass, B is a concrete class that inherits from A and C is a concrete class that inherits from B. Class A declares abstract method originalMethod, implemented in class B. Which of the following statements is true of class C? a. Method originalMethod cannot be overridden in class C—once it has been implemented in concrete class B, it is implicitly final. b. Method originalMethod must be overridden in class C, or a compilation error will occur. c. If method originalMethod is not overridden in class C but is called by an object of class C, an error occurs. d. None of the above.
d. none of the above
Which interface is used to identify classes whose objects can be written to or read from some type of storage or transmitted across a network? a. Comparable b. Runnable c. AutoCloseable d. Serializable
d. serializable
local variable
declared inside the method
C++ uses the _________ to determine access to the members of the pointed-to object
declared type of a pointer
member variable
defined outside of any methods but inside the class
The base class pointer must already point to a __________ for rule 2 to work
derived class object
overloading
different header(# of parameters or type of parameters)
keyword for inheriting a class
extends
interfaces can inclue
final static variables with initialization
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
dynamic binding
if method is overridden, JVM will determine the correct method to invoke at runtime
What is syntax equivalent of extends for classes in interfaces?
implements
keyword for interface
implements
What do you put after a class that multiply inherits from interfaces?
implements <interface names> e.g. class Car implements Drivable, Identifiable {
use super to
initialize any private superclass variables on the first line of the subclass constructor
an abstract class is not
instantiable, the constructor cannot be invoked unless by an inheriting class using a super keyword
comparable interface requires the method
int compareTo(Object obj);
Extends
is the keyword used to inherit the properties of a class. Following is the syntax of extends keyword.
inheritance=
is-a
Describe a deque
items can be added to the front & back - not efficient when adding in middle
extends
keyword must be used to inherit a class
instanceof
keyword that determines if a superclass variable declared type matches the subclassvariable.
polymorphism is all about
late binding
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).
interface:
list of method headers, called abstract classes
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");
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
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.
why shouldn't an abstract method be declared final
object class cannot be overridden must be if a concrete class ever is to be instantiated
polymorphism means
objects can take many forms and still have the same behaviors
polymorphism allows for
objects that inherit a type or implement an interface to be dealt with in the same way, despite the fact that they may have different methods
protected modifier
only accessible by the classes of the same package and the subclasses present in any package
private members
only accessible within the same class as it is declared
superclass method can be written in two ways:
overriding, overloading
visibility /accessibility modifiers
private, default, protected, public
default access modifier for members in interface
public
a subclass can override any ______ of the super class, but cannot override _____
public instance method, private or static methods
declare an interface Animal with methods eat(String food) and travel()
public interface Animal{ public void eat(String food); public void travel(); }
polymorphic reference
refer to different types if objects over time
A _____ ____ can refer to any object created from any class related to it by inheritance.
reference variable
overriding
same header but different implementation
What are examples of an associate container?
set multiset map multimap
You can typecast the base class to the derived class (given base class Animal, derived class Cat with function setMeow)
static_class<Cat*>(animal) -> setMeow(meow);
everything that is public, protected or default if the subclass is in the same package is accessible from inside the
sub class
Dog
subclass
example of using super on method
super.someMethod();
Animal
superclass
polymorphic variable
take on many different rupees, but it is not known which type it has taken on until the program is executing, the decision is made by the run- time environment
late binding
the same name will be associated with different semantics as the program executes
if a class is declared to be abstract
then some methods in the class may have their bodies omitted
if 2 objects are children of the same parent
then, the equals method return true if they reference the same object
if a programmer wants a class to extended
then, the programmer must make private methods and instance data protected
instanceOF is used when
there is a concern about the actual type of the object
if a method defined on a subclass of vehicle needs to be invoked then
type casting must be used
if the superclass has private instance variables, the subclass constructor must
use a method or constructor from the superclass to initialize it
to access a method from superclass,
use the super keyword
how can one create polymorphic references
using inheritance and using interfaces
instance variable
variables within a class but outside any method
ClassCastException at runtime when
you cast to an incorrect type
Power of Polymorphism
Extensibility
Liskov Substitution Principle
Is-A relationship
Chapter Objectives:
1) Define polymorphism and explore its benefits. 2) Discuss the concept of dynamic binding. 3) Use inheritance to create polymorphic references. 4) Explore the purpose of the syntax of Java interfaces. 5) Use interfaces to create polymorphic references. 6) Discuss object-oriented design in the context of polymorphism.
What is the difference between a class and an interface?
A class can be instantiated; an interface cannot. An interface can contain only abstract methods and constants. A class provides the implementation of r an interface.
interface
A collection of abstract methods, used to define a set of operations that can be used to interact with an object.
Polymorphism allows for specifics to be dealt with during: A. execution. B. compilation. C. programming. D. debugging.
A. execution.
Private Access Modifier
Accessible only within the class
Protected Access Modifier
Accessible within package and outside the package but only through inheritance
Which of the following is not possible? A. A class that implements two interfaces. B. A class that inherits from two classes. C. A class that inherits from one class, and implements an interface. D. All of the above are possible.
B. A class that inherits from two classes.
An interface may contain: A. private static data and public abstract methods. B. only public abstract methods. C. public static final data and public abstract methods. D. private static data and public final methods.
C. public static final data and public abstract methods.
Consider classes A, B and C, where A is an abstract superclass, B is a concrete class that inherits from A and C is a concrete class that inherits from B. Class A declares abstract method originalMethod, implemented in class B. Which of the following statements is true of class C? A. Method originalMethod cannot be overridden in class C—once it has been implemented in concrete class B, it is implicitly final. B. Method originalMethod must be overridden in class C, or a syntax error will occur. C. If method originalMethod is not overridden in class C but is called by an object of class C, an error occurs. D. None of the above.
D. None of the above.
Which of the following does not complete the sentence correctly?An interface . A. forces classes that implement it to declare all the interface methods. B. can be used in place of an abstract class when there is no default implementation to inherit. C. is declared in a file by itself and is saved in a file with the D. can be instantiated.
D. can be instantiated.
Declaring a method final means: A. it will prepare the object for garbage collection. B. it cannot be accessed from outside its class. C. it cannot be overloaded. D. it cannot be overridden.
D. it cannot be overridden.
When a superclass variable refers to a subclass object and a method is called on that object, the proper implementation is determined at execution time. What is the process of determining the correct method to call? A. execution time binding. B. execution binding. C. just-in-time binding. D. late binding
D. late binding.
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.8 True or false? You can override a static method defined in a superclass.
False. You can only override accessible instance methods.
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
Abstract method
Method with no body
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
Describe the Comparable interface?
The Comparable interface contains a single method called compareTo, which should return an integer that is less than zero, equal to zero, or greater than zero if the executing object is less than, equal to, or greater than the object which it is being compared, respectively.
dynamic binding
The binding of a method invocation to its definition at run-time. Also called late binding.
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).
How is overriding related to polymorphism?
When a child class overrides the definition of a parent's method, two versions of that method exist. If a polymorphic reference is used to invoke the method, the version of the method that is invoked is determined by the type of the object being referred to, not by the type of the reference variable.
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.
All of the following methods are implicitly final except: A. a method in an abstract class. B. a private method. C. a method declared in a final class. D. static method.
a method in an abstract class.
A(n)_________class cannot be instantiated. A. final. B. concrete. C. abstract. D. polymorphic.
abstract
area
amount of 2D space occupied by the shape; computed differently by different shapes
A ____ to a method can be polymorphic which gives the method flexible control of its arguments.
parameter
The binding of a method invocation to its definition is performed at ____ for a ____ reference.
run-time, polymorphic
Polymorphism
The ability for an object to take on many forms, EX: when a parent class reference is used to refer to a child class object.
polymorphism
The ability to define an operation that has more than one meaning by having the operation dynamically bound to methods of various objects.
Multiple Inheritance
The ability to derive a subclass from multiple classes. Java does not allow this, however does allow a superclass and an interface.
public class XYZ extends XYZparent
extends is what tells the compiler this class XYZ is extending the superclass XYZparent
Which keyword is used to specify that a class will define the methods of an interface? A. uses. B. implements. C. defines. D. extends.
B. implements.
If the superclass contains only abstract method declarations, the superclass is used for: A. implementation inheritance. B. interface inheritance. C. Both. D. Neither.
B. interface inheritance.
It is a UML convention to denote the name of an abstract class in: A. bold. B. italics. C. a diamond. D. there is no convention of the UML to denote abstract classes—they are listed just as any other class.
B. italics
Constants declared in an interface are implicitly A. private. B. static. C. abstract. D. All of the above.
B. static.
polymorphic reference
A reference variable that can refer to different types of objects at different points in time.
11.5 How does a subclass invoke its superclass's constructor?
A subclass can explicitly invoke a suplerclass's constructor using the super keyword.
Which of the following statements about interfaces is false? A. An interface describes a set of methods that can be called on an object, providing a default implementation for the methods. B. An interface describes a set of methods that can be called on an object, not providing concrete implementation for the methods. C. Interfaces are useful when attempting to assign common functionality to possibly unrelated classes. D. Once a class implements an interface, all objects of that class have an is-a relationship with the interface type
A. An interface describes a set of methods that can be called on an object, providing a default implementation for the methods.
Which of the following statements about abstract superclasses is true? A. abstract superclasses may contain data. B. abstract superclasses may not contain implementations of methods. C. abstract superclasses must declare all methods as abstract. D. abstract superclasses must declare all data members not given values as abstract.
A. abstract superclasses may contain data.
Public Access Modifier
Accessible Everywhere
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)
Assigning a subclass reference to a superclass variable is safe: A. because the subclass object has an object of its superclass. B. because the subclass object is an object of its superclass. C. only when the superclass is abstract. D. only when the superclass is concrete.
B. because the subclass object is an object of its superclass.
For which of the following would polymorphism not provide a clean solution? A. A billing program where there is a variety of client types that are billed with different fee structures. B. A maintenance log program where data for a variety of types of machines is collected and maintenance schedules are produced for each machine based on the data collected. C. A program to compute a 5% savings account interest for a variety of clients. D. An IRS program that maintains information on a variety of taxpayers and determines who to audit based on criteria for classes of taxpayers.
C. A program to compute a 5% savings account interest for a variety of clients
A class that implements an interface but does not declare all of the interface's methods must be declared: A. public. B. interface. C. abstract. D. final.
C. abstract.
Classes and methods are declared final for all but the following reasons: A. final methods allow inlining the code. B. final methods and classes prevent further inheritance. C. final methods are static. D. final methods can improve performance.
C. final methods are static.
The UML distinguishes an interface from other classes by placing the word "interface" in above the interface name. A. italics. B. carets. C. guillemets. D. bold
C. guillemets.
Which of the following could be used to declare abstract method method1 in abstract class Class1 (method1 returns an int and takes no arguments)? A. public int method1(); B. public int abstract method1(); C. public abstract int method1(); D. public int nonfinal method1();
C. public abstract int method1();
How do class hierarchies and interface hierarchies intersect?
Class hierarchies and interface hierarchies do not intersect. A class can be used to derive a new class, and an interface can be used to derive a new interface, but these two types of hierarchies do not overlap.
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.
Which statement best describes the relationship between superclass and subclass types? A. A subclass reference cannot be assigned to a superclass variable and a superclass reference cannot be assigned to a subclass variable. B. A subclass reference can be assigned to a superclass variable and a superclass reference can be assigned to a subclass variable. C. A superclass reference can be assigned to a subclass variable, but a subclass reference cannot be assigned to a superclass variable. D. A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable.
D. A subclass reference can be assigned to a superclass variable, but a superclass reference cannot be assigned to a subclass variable.
Consider the abstract superclass below: public abstract class Foo{ private int a; public int b; public Foo( int aVal, int bVal ) { a = aVal; b = bVal; } // end Foo constructor public abstract int calculate(); } // end class Foo Any concrete subclass that extends class Foo: A. Must implement a method called calculate. B. Will not be able to access the instance variable a. C. Neither (a) nor (b). D. Both (a) and (b)
D. Both (a) and (b)
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.
How does inheritance support polymorphism?
In Java, a reference variable declared using a parent class can be used to refer to an object of the child class. If both classes contain a method with the same signature, the parent reference can be polymorphic.
Why is inheritance useful?
It enables polymorphism and code sharing.
What is polymorphism?
Polymorphism is the ability of a reference variable to refer to objects of various types at different times. A method invoked through such a reference is bound to different method definitions at different times, depending on the type of the object referenced.
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
Interface
Special class with no data and only abstract methods
Access Modifier
Specifies accessibility or scope of a field, method, constructor or class
Why is the StaffMember class in the firm example declared as abstract?
The StaffMember class is abstract because it is not intended to be instantiated. It serves as a placeholder in the inheritance hierarchy to help organize and manage the object polymorphically.
superclass / parent class / base class
The class a subclass inherits from.
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.
Interface hierarchy
The hierarchy formed when interfaces are derived from other interfaces. Interface hierarchies are distinct from class hierarchies.
Why is the pay method declared in the StaffMember class, given that it is abstract and has no body at that level?
The pay method has no meaning at the StaffMember level, so it is declared as abstract. But by declaring it there, we guarantee that every object of its children will have a pay method. This allows us to create an array of StaffMember objects, which is actually filled with various types of staff members, and to pay each one. The details of being paid are determined by each class, as appropriate.
super.method(parameters);
This is used to reference a method in a superclass. Usually these are inherited so this is not always necessary unless....
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.
perimeter
distance around the outside of the shape; computed differently based on shape
If you want an is-a relationship or polymorphism, but you don't want to give a subclass access to the code, inheritance won't give you the ______ you need.
encapsulation
An ____ is a collection of abstract methods and therefore cannot be instantiated.
interface
An _____ name can be used to declare an objects reference variable.
interface
An _____ reference can refer to any object of any class that implements that interface.
interface
The relationship between a listener and the component it listens to is established using _____.
polymorphism
binding
the process of determining which method definition is used to fulfill a given method invocation.