Objects Flashcards
What is a field?
A variable that belongs to a class and make up the state of the class
What is a class?
Defines the states
What is an object?
An individual instance of a class
What is the default constructor?
Provided by Java by default, takes no parameters.
Called using new.
Dog bc = new Dog();
What is an initializing constructor?
Used to initialize fields other than default.
public Wizard (String n, int a) {
name = n;
age = a;
}
Why do you use this?
Using this.variableName always refers to the field with the specified name, even
if another variable is closer in scope.
This is called disambiguation (it eliminates ambiguity).
What is a parameterless constructor and why use it?
Once a constructor is defined, Java no longer provides default, but if you want to still have one without parameters, you need to write it!
What is a method?
A function that is a member of a class. May use fields of class. No need to pass a reference to the object.
What is encapsulation?
An object acts like a container, holding state and behavior in place. An object can protect access to fiends and methods using access modifiers.W
What are access modifiers?
A keyword placed before a class, method or field and determines its visibility.
What is an accessor?
Defined for each instance variable that the programmer wants
to make visible outside of the object.
Aka a getter.
What is a mutator?
Defined for each instance variable that the programmer wants to
make modifiable from outside of the object.
Aka a setter.
Why override toString()?
There’s a default, but it’s not useful.
What is the equals(Object) method?
he default implementation works exactly the same as the == operator; it only returns true if an object is compared to itself (it compares identity, i.e. the object’s address).
The author of a class may choose to write their own implementation, typically by following this pattern:
○ Since any type of object may be passed as an argument to the equals(Object) method, you
must first check the make sure that the object is an instance of the same class.
○ Java is a statically typed language: before you can access the state and behavior in the object, you must cast it into a variable of the correct type.
○ Compare each of the important fields in both
instances to see if they match.
This kind of comparison is called
“deep equality.”
@Override
public boolean equals(Object c) {
if(c instanceof Car) {
Car car = (Car) c;
return car.vin == this.vin;
} else {
return false;
}
}
What is the difference between actual and reference type?
The actual type is specified when new is
used to create the new object.
The reference type determines which state
and behavior can be used, regardless of
what the actual type is.
Object obj = new Wizard(); can’t use methods set by Wizard since its ref type is Object.