Chapter 7 Flashcards
What is an object in Java?
An object is an instance of a class that has state (attributes) and behavior (methods).
What is a class in Java?
A class is a blueprint for creating objects. It defines attributes (fields) and behaviors (methods).
How do you define a class in Java?
Using the class
keyword:
```java
class Car {
String model;
int year;
}
~~~
How do you create an object in Java?
Using the new
keyword:
```java
Car myCar = new Car();
~~~
What is a constructor in Java?
A special method used to initialize objects. It has the same name as the class and no return type.
What is the default constructor in Java?
A constructor that takes no arguments and is provided by Java if no other constructor is defined.
How do you define a constructor in Java?
```java
class Car {
String model;
int year;
Car(String m, int y) {
model = m;
year = y;
}
}
~~~
What is method overloading?
Defining multiple methods with the same name but different parameters.
What is the this
keyword in Java?
Refers to the current instance of a class, used to differentiate instance variables from parameters.
What are instance variables?
Variables declared inside a class but outside methods. Each object has its own copy.
What are instance methods?
Methods that operate on instance variables and belong to an instance of a class.
What is encapsulation?
The practice of keeping fields private and providing access via public methods (getters/setters).
What are accessor methods?
Methods that retrieve the values of private variables (getters).
What are mutator methods?
Methods that modify the values of private variables (setters).
What is the static
keyword used for?
Declares class-level variables and methods that belong to the class rather than instances.
What is the difference between instance and static variables?
Instance variables belong to objects, while static variables belong to the class and are shared.
What is method chaining?
Calling multiple methods on the same object in a single statement.
What is garbage collection in Java?
Automatic memory management that removes unused objects to free memory.
What is the finalize()
method?
A method called by the garbage collector before an object is removed from memory.
How can you prevent object modification in Java?
Use the final
keyword to make fields immutable and remove setters.