Unit 5 Flashcards
What is a class in Java?
A blueprint for creating objects; defines fields and methods.
What is an instance variable?
A variable defined in a class for which each object has its own copy.
Where are instance variables declared?
Inside the class
What is a constructor?
A special method used to initialize new objects of a class.
How do you define a constructor?
It has the same name as the class and no return type.
What does the new keyword do?
It creates a new object and calls a constructor.
Can a class have more than one constructor?
Yes
What is constructor overloading?
Having multiple constructors with different parameters.
What happens if no constructor is written?
Java provides a default no-argument constructor.
What is an accessor method?
A method that returns the value of a private field (getter).
How do you write an accessor method?
public int getValue() { return value; }
What is a mutator method?
A method that modifies the value of a field (setter).
How do you write a mutator method?
public void setValue(int newVal) { value = newVal; }
What is the purpose of the this keyword?
It refers to the current object
What is scope in Java?
The region of code where a variable can be accessed.
What is local scope?
A variable declared inside a method; only accessible in that method.
What is instance scope?
A variable declared at the class level; accessible in all instance methods.
Can local variables have the same name as instance variables?
Yes
What is a static variable?
A variable shared among all instances of a class.
What is a static method?
A method that belongs to the class rather than an object.
How do you call a static method?
Use the class name: ClassName.methodName();
Can static methods access instance variables?
No
What is method overloading?
Creating multiple methods with the same name but different parameter lists.
What is encapsulation?
The practice of keeping fields private and providing access via methods.