Unit 9 APCSA
what should you declare in a subclass?
In a subclass, one should declare any new variables (instance or class) or methods that are specific to the subclass (and absent in the superclass).
How can a subclass method call an overridden superclass method?
super.methodname( );
9-1-4: In Java how many parents can a class have?
1
As seen in the code below, the equals method that is inherited from the Object class only returns true if the two objects references refer to the ___
same object.
a subckass inherits a ll public methds from its supercass, and these maethods remain public in t he
subclass
true/false: constructors are not inherited
true
when should you only use inheritance
Only use inheritance when the child class is really a type of the parent class, otherwise use association.
what does it mean for a method to be overloaded?
Overloaded methods are those that share a name but take different parameters.
If a subclass has no call to a superclass constructor then the compiler will automatically add a
super() call as the first line in a constructor.
9-1-3: If I had a class ParkingGarage should it inherit from the class Vehicle?
✔️ No, a parking garage is not a kind of vehicle. Instead it has vehicles in it which implies that the ParkingGarage class would have a field that tracks the vehicles in it.
Look at this code: Highway r3 = new Road("Sullivan Street"); // line 3 What is instantiated as what in this code
A Highway variable instantiated as an object of type Road (THIS CANNOT BE DONE), because not every road is a highway
When should you make a call to the super class' constructor?
A call to a superclass constructor must come at the beginning of the subclass's constructor.
Under what circumstances would a subclass need to override a superclass method?
A subclass will override a superclass method when the method provided in the superclass needs to change. (making the method specific to the subclass)
9-1-1: If you don't specify the parent class in a class declaration which of the following is true?
B. It inherits from the Object class.
9-1-8: What Java keyword is used to set up an inheritance relationship between a subclass and a superclass?
C. extends
to override an inherited method, the method in the child class mut have the same
nam, parameter list, and return type (or subclass or the return type) as the parent method. Any method that is clled must be defined within its own class or superclass.
what is super.toString()
In a subclass, toString() can call the superclass toString() method using super.toString() and then add on its own attributes.
what is the child class or subclass
The class that is inheriting is called the child class or subclass.
In java, all classes can inherit what from another class
attributes (instance variables) and behaviors (methods) from another class.
if a class has no constructor in JAVA, the compiled will add a
no-artument constructor - a no argument constructor is one that doesn't have any paramters, for example: public Person()
In Java, the class Object is at the ___ of hierarchy. Every class in Java ___ from Object and is-an ___.
top inherits Object
true or false: subclasses inherit all the private instance variables in a superclass that they extend, but they cannot directly access them since they are private
true
9-1-2: If the class Vehicle has the instance fields make and model and the class Car inherits from the class Vehicle, will a car object have a make and model?
yes Yes, a child class inherits all the parent class object field and methods.
// Create a class constructor for the Main class what is a constructor - shown in definition
// Create a Main class public class Main { int x; // Create a class attribute // Create a class constructor for the Main class public Main() { x = 5; // Set the initial value for the class attribute x public class Main{ is the creation of the main class public Main() is the constructor for the main class
has a relationship or association relationship
Another type of relationship between classes is the has-a relationship or association relationship. Use this when the object of one class contains a reference to one or more of another class. For example, a course can have many course periods associated with it as shown below. The 1 near the Course means that 1 course object is associated with the number shown near the other class. In this case it is * which means 0 to many. So one course is associated with 0 to many course periods.
9-1-7: An online site shows information about Books and Authors. What kind of relationship do these two classes have?
C. A has-a relationship. The Book class has an Author attribute.Check MeCompare me ✔️ A Book has an Author associated with it. Note that you could also say that an Author has many Books associated with it.
9-1-6: An online store is working on an online ordering system for Books and Movies. For each type of Published Material (books and movies) they need to track the id, title, date published, and price. Which of the following would be the best design?
C. Create the class PublishedMaterial and have Book and Movie inherit from it all the listed attributes. ✔️ We will need to get objects based on their type so we should create classes for Book and Movie. They have common attributes so we should put these in a common superclass PublishedMaterial.
How do you initialize inherited private variables if you don't have direct access to them in the subclass?
In Java you can put a call to the parent constructor using as the first line in a subclass constructor. In Java, the superclass constructor can be called from the first line of a subclass constructor by using the keyword super and passing appropriate parameters, for example super(); or super(theName); as in the code below. The actual parameters given to super() are used to initialize the inherited instance variables, for example the name instance variable in the Person superclass.
what is specialization
Inheritance is also useful for specialization which is when you want most of the behavior of a parent class, but want to do at least one thing differently and/or add more data. The example below can also be seen as specialization. An employee is a person but also has a unique id. A customer is a person, but also has a credit card.
In the last lesson on inheritance hierarchies, we were actually seeing polymorphic behavior at run-time in the following ways.
Polymorphic assignment statements such as Shape s = new Rectangle(); Polymorphic parameters such as print(Shape) being called with different subclass types. Polymorphic array and ArrayList types such as Shape[] shapeArray = { new Rectangle(), new Square() }; In all of these cases, there are no errors at compile-time because the compiler checks that the "subclass is-a superclass" relationship is true. But at run-time, the Java interpreter will use the object's actual subclass type and call the subclass methods for any overriden methods. This is why they are polymorphic - the same code can have different results depending on the object's actual type at run-time.
wat is polymorphism
Polymorphism is a big word that you can break down into "poly" which means many and "morphism" which means form. So, it just means many forms. In Java it means that the method that gets called at run-time (when the code is run) depends on the type of the object at run-time.
what is overring methods
Sometimes, we want to modify existing inherited methods. This is called overriding methods. Overriding an inherited method means providing a public method in a subclass with the same method signature (method name, parameter type list and return type) as a public method in the superclass. The method in the subclass will be called instead of the method in the superclass. One common method that is overriden is the toString() method. The example below shows a similar method called greet().
what is parent class or superclass
The class being inherited from is called the parent class or superclass.
What are the two most common errors when extending the functionality of a superclass method?1)2)
The two most common errors made while extending a superclass are: 1.)Overloading unintentially (instead of overriding) 2.) Forgetting to explicitly use a superclass method instead of a subclass method.
how do you call a method in a superclass that has been overriden?
To call an overrident method, use the reserved would super (in place of this). For example, another deposit (x) would deposit x collars into some type of banking account use the deposit method given in the BankAccount class(superclass)
what is JAVA keyword extends
To make a subclass inherit from a superclass, use the Java keyword extends with the superclass name when creating a new subclass as shown below.
to write your own equals method you must
Use the public boolean equals(Object other) method signature Type cast other to your Classname Return whether this object's attribute(s) equals the other object's attribute(s) with == for primitive types like int and double, or equals for reference types like String or another class.
Class B inherits from class A. Describe the order in which the class's constructors execute when a class B object is created.
When Class B's constructor is invoked, the default Class A constructor is executed FIRST (unless a specific call to a different Class A constructor is written)
Does a subclass have access to private instance variables from its superclass? Explain your answer in a complete sentence.
a subclass does not have access to variables of the superclass that are declared as private. To access them, the subclass must call the accessor methods of the superclass.
any class can override the inherited equals method by providing a method with the same
method signature (method name and parameter list) and return type. The provided method will be called instead of the inherited one, which is why we say that the new method overrides the inherited method. The Person class below overrides the inherited equals method.
If a parent class isn't specified using the extends keyword, the class will inherit from the ___ class.
object
Inheritance means that an object of the child class automatically includes the ___
object instance variables and methods defined in the parent class.
If a method in a subclass has the same name as a method in the superclass, but uses a different parameter list, does the subclass method overload or override the superclass method?
overload
If a method in a subclass has the same signature as a method in the superclass, does the subclass method overload or override the superclass method?
override
The toString() method is a common method that is ___. A subclass can override the superclass toString() method and call the___before adding on its own____.
overriden super.toString() instance variables
Another advantage of an inheritance hierarchy is that we can write methods with ___and pass in ___. For example, the print(Shape) method below could be called with many different Shape subclasses and work for Rectangles, Squares, etc.
parameters of the superclass type subclass objects to them
when one thing inherits from another, we can say that it is the same kind of thing as the
parent class(the class it inherits from) For example, a car is a kind of vehicle. This is sometimes called the is-a relationship, but more accurately it's a is-a kind of relationship. A motorcycle is another kind of vehicle. All vehicles have a make, model, and year that they were created. All vehicles can go forward, backward, turn left and turn right.
code for "In the code, the Course class has an array or ArrayList of CoursePeriod objects as an attribute inside it."
public class Course { private ArrayList<CoursePeriod> periodList; }"
code for "CoursePeriod has a Course attribute inside it to hold the information about the Course."
public class CoursePeriod { private Course courseInfo; private int period; }
are subclasses able to modify methods from the superclass
subclasses can modify the methods of superclasses by overriding them. To override method, the subclass's version must have the same header, i.e., it must have the same name and take the same parameters as the original method of the superclass
Of a superclass and a subclass, which refers to the more general class? ____________________
superclass
A superclass reference variable can hold an object of that ___ or of any of its ___. For example, a Shape reference variable can hold a Rectangle or Square object. (This is a type of polymorphism which will be defined in the next lesson).
superclass subclasses
You cannot declare a variable of the subclass and put in a ___ For example, a Square reference cannot hold a Shape object because not all Shapes are Squares. The code below will give an "Incompatible types: Shape cannot be converted to Square" error (although you could use a type-cast to get it to be a (Square)).
superclass object.
Regardless of whether the superclass constructor is called implicitly or explicitly, the process of calling superclass constructors continues until
the Object constructor is called since every class inherits from the Object class.
But, if the inherited instance variables are private, which they should be, the child class can not directly access
the them using dot notation. The child class can use public accessors (also called getters or get methods) which are methods that get instance variable values and public mutators (also called modifier methods or setters or set methods) which set their values.
Sometimes you want the subclass to do more than what a superclass' method is doing. You want to still execute the superclass method, but you also want to override the method to do something else. But, since you have overridden the parent method how can you still call it? why should you use super.method()
to force the parent's method to be called
what are the two uses of the keyword super
1..super(); or super(arguments); calls just the super constructor if put in as the first line of a subclass constructor. 2.super.method(); calls a superclass' method (not constructors). The keyword super is very useful in allowing us to first execute the superclass method and then add on to it in the subclass.
9-5-6: Which of the following reasons for using an inheritance hierarchy are valid? 1.Object methods from a superclass can be used in a subclass without rewriting or copying code. 2.Objects from subclasses can be passed as arguments to a method that takes an argument of the parent type. 3.Objects from subclasses can be stored in the same array of the parent type. 4.All of the above 5.None of the above
4 ✔️ All of these are valid reasons to use an inheritance hierarchy.
a java class can only inherit from
one parent class
note about compile usig declared type to check that the method youre trying t use are avaialbe to an object of that type
At compile time, the compiler uses the declared type to check that the methods you are trying to use are available to an object of that type. The code won't compile if the methods don't exist in that class or some parent class of that class. At run-time, the actual method that is called depends on the actual type of the object. Remember that an object keeps a reference to the class that created it (an object of the class called Class). When a method is called at run-time the first place that is checked for that method is the class that created the object. If the method is found there it will be executed. If not, the parent of that class will be checked and so on until the method is found.
Why is using a superclass reference for subclass objects useful?
Because now, we can write methods with parameters of type Shape or have arrays of type Shape and use them with any of its subclasses as seen in the next sections.
9-5-3: A class Student inherits from the superclass Person. Which of the following assignment statements will give a compiler error?
D. Student s = new Person();Check MeCompare me ✔️ This is not allowed because a Person is not always a Student.
overriding a method
Don't get overriding a method confused with overloading a method! Overloading a method is when several methods have the same name but the parameter types, order, or number are different. So with overriding, the method signatures look identical but they are in different classes, but in overloading, only the method names are identical and they have different parameters.
is-a substitution test
If you aren't sure if a class should inherit from another class ask yourself if you can substitute the subclass type for the superclass type. For example, if you have a Book class and it has a subclass of ComicBook does that make sense? Is a comic book a kind of book? Yes, a comic book is a kind of book so inheritance makes sense. If it doesn't make sense use association or the has-a relationship instead.
what is an inheritance heirarchy
If you have multiple subclasses that inherit from a superclass, you can form an inheritance hierarchy. Every subclass is-a or is a kind of the superclass. For example, here is an inheritance hierarchy of Shapes. Square is-a Rectangle and a subclass of Rectangle. Rectangle is-a Shape and a subclass of Shape. In Java, the class Object is at the top of hierarchy. Every class in Java inherits from Object and is-an Object.
how to override the equals method
If you want to change how the inherited equals method works you can override it so that the new method is called instead of the inherited one. The String class overrides the inherited equals method to return true when the two objects have the same characters in the same order as shown in the code below.
declared compile time type vs actual run time type
In Java an object variable has both a declared (compile-time) type and an actual (run-time) type. The declared (compile-time) type of a variable is the type that is used in the declaration. The actual (run-time) type is the class that actually creates the object using new. At compile time, the compiler uses the declared type to check that the methods you are trying to use are available to an object of that type. The code won't compile if the methods don't exist in that class or some parent class of that class. At run-time, the actual method that is called depends on the actual type of the object. Remember that an object keeps a reference to the class that created it (an object of the class called Class). When a method is called at run-time the first place that is checked for that method is the class that created the object. If the method is found there it will be executed. If not, the parent of that class will be checked and so on until the method is found.
generalization
Inheritance allows you to reuse data and behavior from the parent class. If you notice that several classes share the same data and/or behavior, you can pull that out into a parent class. This is called generalization. For example, Customers and Employees are both people so it makes sense use the general Person class as seen below.
equals method
One of the important things that gets inherited from the Object superclass is the equals(Object obj) method. This method is used to test if the current object and the passed object called obj are equal. But what does that mean?
what is inheritance based polymorphism
This type of polymorphism is called inheritance-based polymorphism. You have a common parent class, but the behavior is specified in the child class.
Using inheritance hierarchies, we can create ___ and ___ using the ___ type and put in values that are of the ___ type. This can be very useful! For example, here is a Shape array and a Shape ArrayList that can hold any objects of the Shape subclasses.
arrays ArrayLists superclass subclass
Remember that an object always keeps a reference to the ____and always looks for a _____. If it finds the method in the class that created it, it will execute that ___. If it doesn't find it in the class that created it, it will look at the ____ of that class. It will keep looking up the ancestor chain until it finds the ____, all the way up to the ___ class. The method has to be there, or else the code would not have ____.
class that created it method during execution starting in the class that created it method parent method Object compiled
The keyword super can be used to call a superclass'es ____-
constructors and methods
to overload a method, the method name must have the same name, but the paramter list must be
different in some way. It can have a different number of parameters, different types of parameters, and/or different order for the parameter types. The return type can also be different
If you leave off the extends keyword when you declare a class then the class will inherit
from the Object class that is already defined in Java.
how to do a uml class diagram
in a class diagram, you denote inheritance by a solid arrow with a "hollow triangle" tip that points to the superclass.
One of the main reasons to use an inheritance hierarchy is that the instance variables and methods from a superclass are ___.
inherited and can be used in a subclass without rewriting or copying code
Explain the difference between methods in a subclass that are inherited, overridden & new.
inherited methods come directly from a superclass. Overridden methods are present in a super class but "replaced" with a new version in a subclass, new methods are completely unique to the subclass and absent in the superclass.
be sure to provide be sure to use an explicit call to
no argument constructors in parent classes super() as the first line in the constructors of subclasses