Chapter 8 Flashcards
How do we prevent a class to be extended?
Using the final modifier on the class.
Given the following code, how do we print the variable in the parent class?
class Mammal { String type = "mammal"; }
public class Bat extends Mammal { String type = "bat";
public String printParentType(){ return ... //code here } }
super.type
What is the difference between super and this?
The super reference is similar to the this reference, except that it excludes any members found in the current class.
Can we call a parent variable using this keyword?
yes, as long as the variable does not exist in the current class.
What does the this keyword do?
example: this.label
Look for label references including the current class. If it cant find any in the current class, it will try and look in inherited classes.
What does the super keyword do?
example: super.label
Look for label references excluding the current class. It will only look at inherited classes.
What are the constraints of a constructor?
- The name must be the same of the class (case sensitive)
- It cannot have a return type.
- It cannot have a parameter of type var.
Can a class have multiple constructors?
yes, as long as each constructor has a unique signature (paremeters must be different).
Can we call a constructor without the new keyword from outside the class?
no. You need to use the new keyword for a constructor to be called.
What does Java do when the new keyword is used?
It allocated memory for the new object and then looks for a constructor with a matching signature and calls it.
What is the default constructor?
Every class in Java has a constructor wether you code one or not. This Java-created constructor is called a default constructor.
What does a default constructor look like?
A default constructor is a Java created constructor without any parameters or body.
Multiple constructors in a class is called ..
constructor overloading.
How do we call an overloaded constructor from a constructor within the same class?
using this().
When this() is used with paranthesis, Java calls another constructor on the same instance of the class.
What are the rules of using this() inside a constructor to call another constructor?
- There can only be one this() call
- It must be the first statement in the method
- It cannot refer to its own constructor (loop)
What is the difference between this and this()?
The this keyword refers to an instance of the class, while the this() keyword refers to a constructor call within the class.
What is the difference between super and super()?
The super keyword refers to members of the parent class, while the super() keyword calls a parent constructor.