- True or False: An instance variable cannot be defined inside of
any method.
Ans: False. Instance variables are never defined inside of a method.
Only local variables are defined inside of methods.
- Why are instance variables usually defined to be private?
Ans: Because you don't want just anyone modifying instance variables.
You want to inforce a more controlled access through the public getters
and setters.
- What are getters and setters?
Ans: Methods for getting the value of an instance variable of
for setting or changing the value of an instance variable.
- How do you make instance variables read only?
Ans: Only supply a getter method for that instance variable.
- Write a line of code that (1) declares the instance variable
p of type Person and (2) instanitates a Person object with instance
variable values name="Judy", gender='F', age=19.
Ans:
Person p = new Person("Judy", 'F', 19);
- What happens if you invoke the toString method of a class object
after forgetting to define the toString method in that class?
Ans: The toString method of the Object class will be called, which only
returns the name of the class and its address.
- What is the difference between
String s = "dog"
String t = "dog"
and
String s = new String("dog");
String t = new String("dog");
Ans: When the new operator is not used, both s and t contain the address
of the same string, which contains "dog". When the new operator is not
used, two different objects are created, each containing the string "dog".
- What is the difference between arguments and parameters for
methods?
Ans: Arguments are what you pass in to a method when you call it.
Parameters are used in the definition of a method to tell the method
what to do with the passed in arguments.