APCS: Unit 9
When is "super" used?
-We use super keyword to distinguish between parent class and current class. -super is used to refer immediate parent class instance variable. -super() is used to invoke immediate parent class constructor. -super is used to invoke immediate parent class method. -super is only used for immediated parent, cannot use super.super to call "grandparent"
What opportunity does an abstract method give to the compiler?
An abstract method provides an opportunity for the compiler to do additional error checking
What is a class with no abstract methods called?
Concrete
Which class extends which class?
In Java, we say that the subclass extends the superclass .
Can constructors be inherited?
No
Do all abstract classes contain abstract methods?
No, not all abstract classes have abstract methods
Superclass
The parent class that is being extended.
When does the most common use of polymorphism in OOP occur?
When a parent class reference is used to refer to a child class object.
How are abstract classes declared?
With the "abstract" keyword
What is true about abstract methods? a) They do not have an implementation. b) They do not have a return type. c) They are usually found in a child class. d) All of the above.
a
Consider the following classes: public class Rectangle { private int width, height; public Rectangle(int w, int h) { setDimensions(w, h); } public void setDimensions (int w, int h) { width = w; height = h; } } public class Square extends Rectangle { public Square(int side) { < missing code > } < ... other constructors and methods not shown > } True or false? The following can replace < missing code > in Square's constructor so that it sets both width and height to side: (a) super(side, side); (b) width = side; height = side; super(); (c) super(); width = side; height = side; (d) setDimensions(side, side);
(a) T (b) F (c) F (d) F
Rather than making a method abstract, we can use a regular method with empty braces and no code, or make it return 0 or null. True or false? Programmers prefer abstract methods because: (a) Making a method abstract gives the compiler a chance to verify that the method that overrides it in a concrete subclass has the correct signature. (b) An empty method may mislead developers of client classes into thinking that this method is available and functional.
(a) T (b) T
True or false? The following can be achieved by introducing a common superclass S for two related classes, X and Y: (a) The code shared by X and Y can be factored out into S. (b) A method in a client class can take a parameter of type S and work with both X and Y types of parameters passed to it. (c) References of type X can be assigned to variables of type Y and vice-versa.
(a) T (b) T (c) F
Suppose public class D extends B implements I { ... } D and B are concrete classes and each has a no-args constructor. True or false? The following statement is syntactically correct: (a) Object obj = new B(); (b) B obj = new D(); (c) D obj = new B(); (d) I obj = new D();
(a) T (b) T (c) F (d) T
Consider the following definitions: public class Brush implements Drawable {...} public class Canvas extends JPanel { private Brush currentBrush; ... } public class Painter extends Person { private Canvas canvas; ... } True or false? Based on the code shown, the following describes a relationship between the objects: (a) A Brush IS-A Drawable object (b) A Canvas IS-A JPanel(c) A Canvas HAS-A Brush (d) A Painter IS-A Person (e) A Person HAS-A Canvas (f) A Painter HAS-A Brush
(a) T (b) T (c) T (d) T (e) F (f) F
Consider the following classes: public class SmileyFace { public void draw(Graphics g) { g.drawOval(20, 20, 30, 30); drawEyes(g); drawLips(g); } public void drawEyes(Graphics g) { g.fillOval(28, 28, 5, 5); g.fillOval(38, 28, 5, 5); } public void drawLips(Graphics g) { g.drawArc(25, 25, 20, 20, 225, 90); } } public class StraightFace { public void draw(Graphics g) { g.drawOval(20, 20, 30, 30); drawEyes(g); drawLips(g); } public void drawEyes(Graphics g) { g.fillOval(28, 28, 5, 5); g.fillOval(38, 28, 5, 5); } public void drawLips(Graphics g) { g.drawLine(30, 40, 40, 40); } } (a) Write an abstract superclass Face, factoring out common code from SmileyFace and StraightFace into it. (b) Rewrite SmileyFace as a subclass of Face.
**answers in study guide (#12)
Consider the following class: public class Clock { private int hours, mins; public Clock(int h, int m) { hours = h; mins = m; } public int getHours() { return hours; } public int getMins() { return mins; } public void advance() { mins++; if (mins >= 60) { mins = 0; hours++; } if (hours >= 12) { hours = 0; } } } Write a class AlarmClock as a subclass of Clock. Provide a constructor with four parameters: hours and minutes for setting the clock and hours and minutes for setting the alarm. Redefine the advance method so that it advances the clock, then displays the message "Alarm!" if the clock time is equal to the alarm setting.
**answers in study guide (#13)
Encapsulation
- Encapsulation is one of the four fundamental OOP concepts. The other three are inheritance, polymorphism, and abstraction. -Encapsulation is the technique of making the fields in a class private and providing access to the fields via public methods. If a field is declared private, it cannot be accessed by anyone outside the class, thereby hiding the fields within the class. For this reason, encapsulation is also referred to as data hiding. -Encapsulation can be described as a protective barrier that prevents the code and data being randomly accessed by other code defined outside the class. Access to the data and code is tightly controlled by an interface (we will learn about interfaces in Unit 10). -The main benefit of encapsulation is the ability to modify our implemented code without breaking the code of others who use our code. With this feature Encapsulation gives maintainability, flexibility and extensibility to our code.
Relate abstract classes and superclasses
-An abstract class can only be used as a superclass for other classes that extend the abstract class. -Abstract classes serve as common superclasses for more specific classes.
Purpose of a constructor
-Constructors have one purpose in life: to create an instance of a class. -This can also be called creating an object. -A constructor in a class is one of the first pieces of code to be executed when you instantiate a class. -The purpose of constructors is to have code that initialize the class and prepare the variables that may be required by the class
Why use abstract classes?
-If you need a template for other classes -You want to share code among several closely related classes -You want common functionality for every class as well as different implementation of a method in derived classes for other methods -You expect that classes that extend your abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private).
When you design inheritance 1) Where do you put the common code? 2) What do you tell other more specific classes?
-Put common code in a class -Tell other more specific classes that the common (more abstract) class is their superclass.
Common errors with shadowing instance variables:
1) A subclass has no access to the private instance variables of the superclass: public class SavingsAccount extends BankAccount { public void addInterest() { double interest = getBalance() * interestRate / 100; balance = balance + interest; // Error } . . . } 2) Beginner' s error: "solve" this problem by adding another instance variable with same name: public class SavingsAccount extends BankAccount { private double balance; // Won't solve the problem public void addInterest() { double interest = getBalance() * interestRate / 100; balance = balance + interest; // Compiles but doesn't update the correct balance } . . . }
What is created with these examples (be specific)? 1) Animal d = new Dog(); 2) Animal c = new Cat(); 3) Animal b = new Bird(); 4) Animal[] arr = {d, c, b}; 5) for(Animal x: arr) { x.play(); }
1) creates a Dog object d with an Animal reference 2) creates a Cat object c with an Animal reference 3) creates a Bird object b with an Animal reference 4) creates an array of Animals 5) for each loop that runs through the array of Animals
Assuming the statements SomeSuperClass x = new SomeClass(); x.someMethod(); compile with no errors, what do we need to do to ensure that x.someMethod()calls SomeClass's someMethod? A. Nothing: polymorphism is applied automatically B. Compile SomeSuperClass and SomeClass with the "polymorphism enabled" option C. Define SomeSuperClass with the implements Polymorphism modifier D. Define someMethod in SomeSuperClass as abstract
A
Consider the following class, which represents a window on the screen: public class Alarm extends JFrame { public Alarm() { Timer t = new Timer(1000, this); // delay 1 sec t.start(); } public void actionPerformed(ActionEvent e) { Container c = getContentPane(); c.setBackground(Color.RED); } } Assume that all the necessary import statements are present. The main method of a client class is programmed to create an Alarm-type window, set its position and dimensions, and open it on the screen. What is the result when Alarm and this client class are compiled and executed? A. Alarm won't compile: the compiler will give an error message "undefined symbol: constructor Timer(int, Alarm)" B. The class compiles but the program will be aborted with a NoSuchMethodException C. The program compiles and runs, the window is displayed, but its background never turns red D. The program compiles and runs, the window is displayed, and its background turns red after 1 second
A
Consider the following classes: public abstract class A { public void methodX() { System.out.print("X"); } public abstract void methodY(); } public class C extends A { public void methodY() { System.out.print("Y"); } } What is the result of: A a = new A(); // Line 1 A c = new C(); // Line 2 a.methodX(); // Line 3 c.methodY(); // Line 4 A. Syntax error on Line 1: "Class A cannot be instantiated" B. Syntax error on Line 4: "Undefined symbol, methodY" C. NoSuchMethodException on Line 4 D. Compiles and runs with no errors and displays XY
A
When does a subclass override a superclass?
A subclass method overrides a superclass method if it has the same name and parameter types as a superclass method. --When such a method is applied to a subclass object, the overriding method is executed --No special syntax required to override a superclass method. --Just write a new version of it in the subclass
Inheritance
A way to form new classes based on existing classes, taking on their attributes/behavior. --a way to group related classes --a way to share code between two or more classes
Relate abstract classes to subclasses
Abstract classes are used to provide a template or design for concrete subclasses down the inheritance tree.
Can abstract classes be instantiated?
Abstract classes cannot be instantiated, they can be subclassed
Methods that are declared but undefined
Abstract methods
In subclass, what should be specified?
Added instance variables, added methods, and changed or overridden methods public class SavingsAccount extends BankAccount { private double interestRate; public SavingsAccount(double rate) { Constructor implementation } public void addInterest() { Method implementation } }
How does inheritance extend existing classes?
Adding instance variables and methods class SavingsAccount extends BankAccount { added instance variables new methods }
Inheritance relationship
An inheritance relationship means that the subclass inherits the members of the superclass.
What type of Java object is considered to be polymorphic?
Any Java object that can pass more than one IS-A test. In Java, all Java objects are polymorphic since any object will pass the IS-A test for their own type and for the class Object.
Syntax for creating a subclass
At the beginning of your class declaration, use the extends keyword, followed by the name of the class to inherit from: class MountainBike extends Bicycle { // new fields and methods defining // a mountain bike would go here } -This gives MountainBike all the same fields and methods as Bicycle, yet allows its code to focus exclusively on the features that make it unique. -This makes code for your subclasses easy to read. However, you must take care to properly document the state and behavior that each superclass defines, since that code will not appear in the source file of each subclass.
What happens if you derive your class from a library class and inadvertently give your method the same name and parameters as one of the public methods of that library class? A. The class won't compile B. The class compiles, but the program gives a run-time error when your method is called C. The program runs but may start behaving strangely or stop responding to some commands or events D. Nothing changes, the program works as before
C
Consider the following classes: public class One { private int value; public One() { value = 1; } public int getValue() { return value; } public String toString() { return String.valueOf(getValue()); } } public class Two extends One { public int getValue() { return super.getValue() + 1; } } What is the output from the following code? One n1 = new One(); One n2 = new Two(); System.out.println(n1 + " " + n2); A. 0 1 B. 0 2 C. 1 1 D. 1 2
D
Example of a subclass override a superclass:
Deposit and withdraw methods of the CheckingAccount class override the deposit and withdraw methods of the BankAccount class to handle transaction fees: public class BankAccount { . . . public void deposit(double amount) { . . . } public void withdraw(double amount) { . . . } public double getBalance() { . . . } } public class CheckingAccount extends BankAccount { . . . public void deposit(double amount) { . . . } public void withdraw(double amount) { . . . } public void deductFees() { . . . } }
In this example: Animal d = new Dog(); d.play(); Which play() is really called? The one in Animal, or the one in Dog?
Dog If a Dog object is at the other end of an Animal reference, you still get the Dog version of the method. Always. In other words, it is based on the actual object's class, not the reference type.
Inheritance hierarchy example
Example: Different account types: -Checking account: --No interest --Small number of free transactions per month --Charges transaction fee for additional transactions -Savings account: --Earns interest that compounds monthly -Superclass: BankAccount -Subclasses: CheckingAccount & SavingsAccount
When would this polymorphism example be legal/compile: Animal d = new Dog();
If dog is a subclass of Animal. If the reference type is a class, the object it refers to MUST be either that same type or a subclass of that type.
Why type of relationship does inheritance represent?
Inheritance represents the IS-A relationship between objects: an object of a subclass IS-A(n) object of the superclass.
When we say "members of a class", what do we mean?
Instance variables and methods.
Are instance variables overriden?
Instance variables are not overridden because they don't need to be.
Whenever an object of a subclass is created, what is the first thing Java does?
It calls a constructor of the superclass
What can be used to declare common characteristics of subclasses?
Java Abstract classes
Does a subclass have access to private instance variables of its superclass?
No, unless it is accessed through public methods.
What allows classes to inherit commonly used state and behavior from other classes?
Object-oriented programming
What do abstract classes require?
Subclasses to provide implementations for the abstract methods.
What happens if there is no explicit call to super?
Superclass' no-args constructor is called by default. --BUT, it must be defined. if not defined ⎯ syntax error: cannot find symbol : constructor ...
Subclass
The child class that extends the superclass and inherits its behavior. --Subclass gets a copy of every field and method from superclass
What does a subclass inherit?
The methods of its superclass SavingsAccount collegeFund = new SavingsAccount(10); // Savings account with 10% interest collegeFund.deposit(500); // OK to use BankAccount method with SavingsAccount object
When one class inherits from another, where does subclass inherits from?
The superclass
Does an instance variable define a special behavior? Why is this significant?
They don't define any special behavior, so a subclass can give an inherited instance variable any value it chooses.
How do you invoke superclass constructors? Provide code as well.
To call the superclass constructor, use the super reserved word in the first statement of the subclass constructor: class Vehicle { Vehicle() { System.out.println("Vehicle is created"); } } class Bike5 extends Vehicle { Bike5() { /***right here! super(); //will invoke parent class constructor System.out.println("Bike is created"); } public static void main(String args[]){ Bike5 b=new Bike5(); } }
True or False: Abstract classes have constructors, fields, and/or regular methods
True
True or False: A programmer can specify which of the superclass' constructors to call and what parameters to pass it using the keyword super
True
How do you call a method of the superclass? Provide example code.
Use the "super" reserved word Ex: public class CheckingAccount extends BankAccount { public void deposit(double amount) { transactionCount++; // Now add amount to balance super.deposit(); } }
class hierarchies
Using inheritance, a programmer can define a hierarchy of classes. Class Hierarchies help reduce duplication of code by factoring out common code from similar classes into a common superclass. Multiple levels of inheritance in a hierarchy are allowed. Help reduce duplication of code by letting you write more general methods in client classes.
When do we use abstract methods?
When an operation is performed in a different way for the subclasses forcing subclasses to provide a custom implementation.
What makes an operation a good candidate for an abstract method?
When an operation is performed in a different way, it is a good candidate for an abstract method (forcing subclasses to provide a custom implementation).
Are instance variables declared in the superclass present in subclass objects?
Yes
An abstract class can have constructors a) True b) False c) Well I never
a
Can a concrete object of a child type be assigned to a variable of an abstract parent type? a) Yes b) No c) I can't even d) I REALLY can't even
a
Can an abstract method be defined in a non-abstract class? a) No—if a class defines an abstract method must be abstract. b) No—only classes are abstract, not methods c) Yes—as long as the children are abstract d) Yes—there is no restriction on where abstract methods can be
a
What happens if you create a class but don't create a constructor? a) Java creates a default (no parameter) constructor for you b) There would be a compile-time error. c) There would be a run-time error. d) I don't EVER want to find out
a
What is an advantage of polymorphism? a) The same logic can be used with objects of different types b) Variables can be re-used in order to save memory. c) Making new objects from old objects of like type saves time d) Polymorphism is dangerous and should be avoided.
a
Which header correctly creates a child class Dog which inherits from Pet a) public class Dog extends Pet b) public class Dog implements Pet c) public subclass Dog extends Pet d) public class Dog inherits Pet
a
Which of the following is an example of polymorphism? a) one variable is used with different types of objects b) several different types of objects with its own variable c) when a single parent class has many child classes. d) methods with the same name but different parameter types
a
An abstract class can be instantiated if it contains no abstract methods a) True b) False c) I recognize some of the words in that sentence class CS extends Nonsense
b
What is another name for a child class? a) Superclass b) Subclass c) Kid class d) Parent class
b
What is polymorphism? a) Another word for the parent child relationship. b) If an instance has a different compiletime than runtime type c) When a class inherits methods from an interface. d) Instance variables in an abstract class
b
Which is true? a) Teacher inherits the constructor of Person b) Teacher can add new instance variables & methods. c) Teacher can override private methods in Person d) All of the above are true.
b
Which of the following determines what method will be run? a) The type of the (reference) variable b) The type of the object c) The method itself, methods DO NOT care d) The super class' type
b
Suppose that the following four classes have been declared: public class Foo { public void method1() { System.out.println("foo 1"); } public void method2() { System.out.println("foo 2"); } public String toString() { return "foo"; } } public class Bar extends Foo { public void method2() { System.out.println("bar 2"); } } public class Baz extends Foo { public void method1() { System.out.println("baz 1"); } public String toString() { return "baz"; } } public class Mumble extends Baz { public void method2() { System.out.println("mumble 2"); } } What would be the output of the following client code? Foo[] pity = {new Baz(), new Bar(), new Mumble(), new Foo()}; for (int i = 0; i < pity.length; i++) { System.out.println(pity[i]); pity[i].method1(); pity[i].method2(); System.out.println(); }
baz baz 1 foo 2 foo foo 1 bar 2 baz baz 1 mumble 2 foo foo 1 foo 2
What does overriding a method mean? a) Changing the number of and/or type of parameters of a method b) Changing the return type of a method. c) Writing a method in the child that has same header as parent d) Implementing an abstract method
c
What does the term UML mean? a) United Modem Language b) United Modern Language c) Unified Modeling Language d) Unified Modern Language
c
What is another term for a "Has-A" relationship? a) Inheritance b) Interface c) Association d) Super
c
Which of the following describes an abstract class? a) A class without any subclasses b) A super class with more than one sub class c) A class that can't be instantiated d) Another name for a super (base) class
c
Which of the following is true about abstract methods? a) An abstract method is any method in an abstract class b) An abstract method cannot be inherited c) An abstract method is a method that is declared only (without a body) d) Abstract methods must be overridden by the super-class(es)
c
Can an abstract class define both abstract methods and non-abstract methods? a) No—it must have all one or the other. b) No—it must have all abstract methods. c) Yes—but the child classes don't inherit the abstract methods d) Yes—the child classes inherit both.
d
Can an abstract class have abstract children? a) No—an abstract parent must have only abstract children. b) No—an abstract parent must have no children at all. c) Yes—all children of an abstract parent must be abstract. d) Yes—abstract parents can have abstract and concrete children
d
What is another way to describe a parent-child relationship? a) "Has-A" b) "Does-A" c) "Gets-A" d) "Is-A"
d
What is true about abstract classes? a) They may contain non-abstract methods. b) An instance of abstract classes may not be created. c) They may contain instance variables. d) All of the above are true.
d
When you System.out.println() a reference type variable, what happens? a) The @Override method is called b) Java magically creates a String version of the object c) There will be a compile-time error d) The object's toString() method is implicitly called
d
Inheritance syntax (example)
public class name extends superclass { public class Secretary extends Employee { ... } - By extending Employee, each Secretary object now: -- receives a getHours, getSalary, getVacationDays, and getVacationForm method automatically -- can be treated as an Employee by client code
Polymorphism
the ability of an object to take on many forms