Chapter 11: How to work with inheritance Flashcards
What is inheritance
When inheritance is used, a subclass inherits the fields and methods of a superclass. Then, when you create an object from the subclass, that subclass can use these fields and methods. The subclass can also provide its own fields and methods that extend the superclass, and it can override fields and methods of the superclass by providing new code for them.
What is the Object Class
The superclass for all Java classes. In other words, every class automatically inherits the Object class.
What are the methods of the Object Class
toString(), equals(Object), getClass(), clone(), hashCode()
What are the 4 access modifiers
private - available within the current class public - available to classes in all packages protected - available to classes in the same package and to subclasses no keyword coded - available to classes in the same package
How is a subclass created
public class SubclassName extends SuperClassName{}
How do you override a method in a subclass
@Override
What is polymorphism
is one of the most important features of object-oriented programming and inheritance. Lets you treat objects of different types as if they were the same type by referring to a superclass that’s common to both objects.
What is the instanceOf operator
to check whether a variable is an instance of an object.
How to assign a superclass to a subclass and vice versa
Book b = new Book(); cast Book object to a product Product p = b; cast Product back to a book Book b2 = (Book) p;
How do we test if two objects point to the same memory location
Product product1 = new Product(); Product product2 = product1; if (product1.equals(product2))
How do we test if two objects have the same data
The equals method of the Product class
@Override
public boolean equals(Object object) { }
if (object instanceof Product) { Product product2 = (Product) object; if (code.equals(product2.getCode()) && description.equals(product2.getDescription()) && price == product2.getPrice()) { return true; return false; } } T