Chapter 10 - Thinking In Objects Flashcards
If all the data fields in a class are private and primitive types, and the class doesn’t contain any set methods, is the class immutable?
CHECK THIS
Yes, it’s immutable.
If a class contains only private data fields and no set methods, is the class immutable?
CHECK THIS It depends. If the class contains a get method to a private reference data field (like an array(?)), it can be mutated.
What is the role of the ‘this’ keyword?
The ‘this’ keyword can be used to refer to the calling object. It can also be used inside a constructor to invoke another constructor of the same class
What is important in class design?
Cohesion. A class should describe a single entity. Consistency. Follow Java programming style and naming conventions. A popular style is data fields before constructors before methods. Encapsulation. A class should use the 'private' modifier to hide its data from direct access by clients. Clarity. A class should have a clear contract that is easy to understand. Completeness. A class should provide a variety of ways for customization through properties and methods.
What is the difference between an instance and a static variable?
A variable that is dependent on an instance of the class, i.e. the radius of a circle object, must be an instance variable. A variable that is shared by all instances of a class should be a static variable.
What’s the difference between instance and static methods?
If a method is not dependent on a specific instance of a class, the method should be static. I.e. the method ‘factorial(n)’ should be static, because it is not dependent on an instance. The method ‘getArea()’ should be an instance method, because it is dependent on a specific geometrical object. Furthermore, for clarity, static methods should be invoked through class name: ‘Math.pow(a, b)’, and instance methods should be invoked through object name: ‘myCircle.getArea()’
How can you make objects out of primitive data types?
You use wrapper classes. Integrer for int: Integer objName = new Integer(int) Or Integer objName = int Same for the other primitive data types.
Analyze the following code: public class Test { public static void main(String[] args) { String firstName = "John"; Name name = new Name(firstName, 'F', "Smith"); firstName = "Peter"; name.lastName = "Pan"; System.out.println(name.firstName + " " + name.lastName); } }
class Name {
String firstName;
char mi;
String lastName;
public Name(String firstName, char mi, String lastName) { this.firstName = firstName; this.mi = mi; this.lastName = lastName; } }
The program displays John Pan