Thinking In Objects Flashcards Preview

► Java > Thinking In Objects > Flashcards

Flashcards in Thinking In Objects Deck (8)
Loading flashcards...
1
Q

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?

A

CHECK THIS

Yes, it’s immutable.

2
Q

What is the role of the ‘this’ keyword?

A

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

3
Q

What is important in class design?

A
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.
4
Q

What is the difference between an instance and a static variable?

A

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.

5
Q

If a class contains only private data fields and no set methods, is the class immutable?

A
CHECK THIS
It depends. If the class contains a get method to a private reference data field (like an array(?)), it can be mutated.
6
Q

What’s the difference between instance and static methods?

A

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()’

7
Q

How can you make objects out of primitive data types?

A
You use wrapper classes. Integrer for int: 
Integer objName = new Integer(int)
Or
Integer objName = int
Same for the other primitive data types.
8
Q
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;
  }
}
A

The program displays John Pan