Chapter 8 Flashcards
What does each instance of a class have in Java?
Its own copy of instance variables.
Example:
Each Rectangle object has its own length and width.
What are instance methods, and how are they used?
Instance methods require an object instance to be created. They typically interact with instance fields or calculate values.
What is a static field or method?
A static field or method belongs to the class, not any instance, and is accessed using the class name.
How do you declare a static field in Java?
Place the static keyword between the access specifier and the type.
Example: private static int instanceCount = 0;
How are static methods declared and used?
Declared using static between the access modifier and return type. They can be called without creating an instance.
Example:
java
Copy code
public static double milesToKilometers(double miles);
Metric.milesToKilometers(1.0);
What happens when an object is passed to a method?
The reference value (address) is passed, allowing the method to modify the object contents.
Can methods return objects?
Yes, methods can return references to objects. However, only the object’s address is returned, not a copy
What does the toString method do in Java?
Converts an object to a string representation, used implicitly in println and string concatenation.
How do you compare objects in Java?
Use equals() to compare contents. The == operator compares memory addresses.
What are the two types of object copying?
Reference Copy: Copies the address, not the object.
Deep Copy: Creates a new instance and copies the values.
What is object aggregation?
Creating an instance of one class as a reference in another, forming a “has-a” relationship.
What does the this keyword do?
Refers to the current object instance, resolves shadowing, and supports constructor chaining.
What is an enum in Java?
A predefined list of constants.
Example:
java
Copy code
enum Day { MONDAY, TUESDAY, … }
Name three methods available for an enum.
toString(): Returns the constant’s name.
ordinal(): Returns the position of the constant.
compareTo(): Compares based on ordinal values.
How does Java manage memory for unused objects?
The Garbage Collector reclaims memory for objects without references. Use null to release an object.