Chapter 4.1: Objects and Classes

Chapter 4.1: Objects and Classes · Study Questions
Class and objectConstructor chainingInitializersstatic membersPass by valueReferences and this== and equalsWrapper classesenumInner classes
Sercan KÜLCÜ · Giresun University · Computer Engineering

Multiple Choice · Object-Oriented Programming

Question 1: Class and Object

Which statement is true about two objects created from the same class with new?

A: A class is a blueprint; every object carries its own copy of the instance fields. The method code exists only once, and this decides which object's data it works with (C is wrong). Sharing fields applies only to static fields (B).

Multiple Choice · Constructors

Question 2: Names and Default Values

Does the program compile? If it does, what does it print?

public class Example2 {
  private static int $;
  public static void main(String[] args) {
    String value_1 = "1";
    System.out.print($);
    System.out.print(value_1);
  }
}

B: $ is a valid name (letters, digits, _ and $; it cannot start with a digit). Fields get default values: a static int field is 0. The two print calls write side by side without a line break: 01. Local variables, on the other hand, get no default value; they cannot be read before being given one.

Output Question · Constructors

Question 3: A Box with Three Constructors

In main, new Box(); System.out.println(); new Box(1); System.out.println(); is run. What does the program print?

class Box {
  int width;
  Box() {
    this(2);
    System.out.print("A" + width);
  }
  Box(int width) {
    this(width, width * 3);
    System.out.print("B" + width);
  }
  Box(int width, int height) {
    this.width = width + height;
    System.out.print("C" + this.width);
  }
}
Show answer
C8B2A8
C4B1
  • Box() first calls this(2), which calls this(2, 6): width = 2 + 6 = 8 → C8.
  • As the chain unwinds, each constructor runs the rest of its own body: B2 (the parameter width = 2), then A8 (the field width = 8).
  • new Box(1): this(1, 3) → C4, then B1. The no-argument constructor never runs.

Multiple Choice · Constructors

Question 4: A Constructor Written with void

What happens when Book b = new Book("Java"); is written in main?

class Book {
    String title;
    public void Book(String title) {
        this.title = title;
    }
}

C: A constructor has no return type, not even void. Since this class has no constructor at all, the compiler adds only the no-argument default constructor; no suitable constructor is found for new Book("Java"): constructor Book in class Book cannot be applied to given types.

Step-by-Step Trace · Constructors

Question 5: A Constructor Chain with this(...)

Two objects are created. In which constructor, and in what order, do the fields get their values? What does the program print?

StackHeapTrColor()thismain()e?#1 TrColorcolornullcoats0

new allocates the object on the heap; the fields get default values: color = null, coats = 0. The no-argument constructor starts.

StackHeapTrColor(String)thiscolor"white"TrColor()thismain()e?#1 TrColorcolornullcoats0

this("white") calls the other constructor for the same object: a new frame opens, and in both, this points to #1.

StackHeapTrColor(String)thiscolor"white"TrColor()thismain()e?#1 TrColorcolor"white"coats0

this.color is the object's field, and the color on the right is the parameter: the field becomes "white".

StackHeapTrColor(String)thiscolor"white"TrColor()thismain()e?#1 TrColorcolor"white"coats1

The constructor with a parameter sets coats to 1 and finishes; its frame closes.

StackHeapTrColor()thismain()e?#1 TrColorcolor"white"coats2

The no-argument constructor continues where it left off: coats = 2. The last write wins; the value 1 was overwritten.

StackHeapmain()e#1 TrColorcolor"white"coats2

Both constructors are done; the reference, which is the value of the new expression, is assigned to e.

StackHeapmain()ef#1 TrColorcolor"white"coats2#2 TrColorcolor"blue"coats1

The second object is built directly with TrColor(String): "blue" and 1. This time the no-argument constructor never runs.

StackHeapmain()ef#1 TrColorcolor"white"coats2#2 TrColorcolor"blue"coats1

The output: white 2 and blue 1. Each object carries its own fields.

public class TrColor {
  private String color;
  private int coats;
  public TrColor() {
    this("white");
    coats = 2;
  }
  public TrColor(String color) {
    this.color = color;
    coats = 1;
  }
  public static void main(String[] args) {
    TrColor e = new TrColor();
    TrColor f = new TrColor("blue");
    System.out.println(e.color + " " + e.coats);
    System.out.println(f.color + " " + f.coats);
  }
}

Output Question · Constructors

Question 6: A Chain of Three Constructors

Three overloaded constructors call each other with this(...). What does the program print?

class Counter {
    int value;
    String name;
    Counter() {
        this(10);
        name = "first";
    }
    Counter(int v) {
        value = v;
    }
    Counter(String n, int v) {
        this(v * 2);
        name = n;
    }
}
// in main:
Counter c1 = new Counter();
Counter c2 = new Counter(5);
Counter c3 = new Counter("x", 4);
System.out.println(c1.value + " " + c1.name);
System.out.println(c2.value + " " + c2.name);
System.out.println(c3.value + " " + c3.name);
Show answer
10 first
5 null
8 x
  • new Counter(): first this(10) sets value = 10, then name = "first".
  • new Counter(5): only value is assigned; since name is never assigned, the String field has its default value, null.
  • new Counter("x", 4): this(8) → value = 8, then name = "x".
  • this(...) must be on the first line of the constructor.

Output Question · Fields

Question 7: Initialization Order

main is: System.out.print("M"); new B(); new B(); System.out.println();. What does the program print?

class B {
  static { System.out.print("S"); }
  int x = show("F");
  { System.out.print("I"); }
  B() { System.out.print("C"); }
  static int show(String s) {
    System.out.print(s);
    return 1;
  }
}
Show answer
MSFICFIC
  • main first prints M; class B is loaded at the first new B() and the static block runs once: S.
  • For every object the order is: field initial values and instance initializer blocks in the order they are written (F, I), then the constructor body (C).
  • For the second object the static block does not run again: FIC.

Multiple Choice · Methods

Question 8: A Missing return

Which statement is true about this method?

static int sign(int x) {
  if (x > 0) return 1;
  else if (x < 0) return -1;
}

C: Every path of a method that returns int must end with return. When x == 0, both conditions are false and the end of the method is reached; the compiler sees this and does not run the program at all. The fix: add return 0; at the end.

Spot the Bug · static Members

Question 9: An Instance Member from a static Context

Does the program compile? If not, which lines give which error? Suggest two different fixes.

public class Tally {
  int count = 0;
  void increment() { count++; }
  public static void main(String[] args) {
    increment();
    System.out.println(count);
  }
}
Show answer

It does not compile; two errors:

error: non-static method increment()
  cannot be referenced from a
  static context
error: non-static variable count
  cannot be referenced (same ending)

main is static: it has no object and no this; instance members need an object.

  • Create an object: Tally t = new Tally(); t.increment(); System.out.println(t.count); → 1
  • Make the members static: static int count and static void increment() → 1. Now all objects share the counter.

Step-by-Step Trace · static Members

Question 10: A static Ticket Counter

Each ticket takes a number from the shared counter. What does the line a.lastId = 500; change? What does the program print?

Class field: Ticket (static)lastId100StackHeapmain()a?b?c?

When the class is loaded, the static field is created once: lastId = 100. There are no objects yet.

Class field: Ticket (static)lastId101StackHeapTicket()thismain()a?b?c?#1 Ticketid0

The first object: id is 0 at first. The constructor increments the shared counter: 101.

Class field: Ticket (static)lastId101StackHeapTicket()thismain()a?b?c?#1 Ticketid101

id = lastId: the current value is copied into the object's own field.

Class field: Ticket (static)lastId101StackHeapmain()ab?c?#1 Ticketid101

The constructor finishes; a points to the first ticket.

Class field: Ticket (static)lastId102StackHeapmain()abc?#1 Ticketid101#2 Ticketid102

The same steps for the second object: the counter is 102, #2.id = 102. #1.id does not change.

Class field: Ticket (static)lastId500StackHeapmain()abc?#1 Ticketid101#2 Ticketid102

a.lastId is written through an object, but the field is static: the compiler treats it as Ticket.lastId = 500. There is no lastId inside the object.

Class field: Ticket (static)lastId501StackHeapTicket()thismain()abc?#1 Ticketid101#2 Ticketid102#3 Ticketid501

The third ticket continues from 500: the counter is 501, #3.id = 501.

Class field: Ticket (static)lastId501StackHeapmain()abc#1 Ticketid101#2 Ticketid102#3 Ticketid501

The output: 101 102 501 and 501 501. b.lastId reads the same single field too.

class Ticket {
  static int lastId = 100;
  int id;
  Ticket() {
    lastId++;
    id = lastId;
  }
}
public class TrTicket {
  public static void main(String[] args) {
    Ticket a = new Ticket();
    Ticket b = new Ticket();
    a.lastId = 500;
    Ticket c = new Ticket();
    System.out.println(a.id + " " + b.id + " " + c.id);
    System.out.println(Ticket.lastId + " " + b.lastId);
  }
}

Multiple Choice · References and this

Question 11: Which i?

What does the program print? (Each number on a separate line.)

public class Example5 {
  private static int i = 1;
  public static void main(String[] args) {
    System.out.println(i);
    int i = 2;
    Example5 example = new Example5();
    System.out.println(i);
    example.show();
  }
  public static void show() {
    System.out.println(i);
  }
}

D: At the first println there is no local i yet; the static field is read: 1. After the local i = 2 is declared, it shadows the field in main: 2. In the frame of show there is no local i, and main's local is not visible: 1. A local variable with the same name as a field is legal (C is wrong).

Output Question · References and this

Question 12: An Alias

These lines run in main. What does the program print? How many Box objects are created?

class Box {
  int width;
  Box(int width) { this.width = width; }
  void grow(int amount) { width += amount; }
}
// in main:
Box a = new Box(4);
Box b = a;
b.grow(3);
a = new Box(1);
a.grow(2);
System.out.println(a.width + " " + b.width);
System.out.println(a == b);
Show answer
3 7
false
  • b = a does not copy the object, it copies the reference: both variables point to the same object. b.grow(3) makes that object go from 4 to 7.
  • a = new Box(1) only binds a to the second object; the first object lives on through b. a.grow(2) → 3.
  • Two objects were created; a and b now point to different objects: false.

Step-by-Step Trace · References and this

Question 13: Pass by Value

The method takes a reference and an int. Which of the four assignments inside the method show up in main? What does the program print?

StackHeapmain()ns?#1 Pointx0

A Point object is created; n holds only its reference.

StackHeapmain()ns1#1 Pointx1

n.x = 1 writes into the object, and s = 1 into the primitive variable on the stack.

StackHeapmove(p, k)pk1main()ns1#1 Pointx1

Java always passes by value: p is a copy of the reference (it points to the same object), and k is a copy of the number.

StackHeapmove(p, k)pk1main()ns1#1 Pointx5

p.x = 5 changes the shared object; this change will be visible through n too.

StackHeapmove(p, k)pk7main()ns1#1 Pointx5

k = 7 changes only the copy; s in main stays 1.

StackHeapmove(p, k)pk7main()ns1#1 Pointx5#2 Pointx0

p = new Point() turns the copied reference toward a new object; n still points to #1.

StackHeapmove(p, k)pk7main()ns1#1 Pointx5#2 Pointx9

9 is written into the new object; #1 is not affected.

StackHeapmain()ns1#1 Pointx5#2 Pointx9

The method ends and its frame is removed; no reference to #2 is left (it is up to the garbage collector). The output: 5 1.

class Point {
  int x;
}
public class TrPassing {
  static void move(Point p, int k) {
    p.x = 5;
    k = 7;
    p = new Point();
    p.x = 9;
  }
  public static void main(String[] args) {
    Point n = new Point();
    n.x = 1;
    int s = 1;
    move(n, s);
    System.out.println(n.x + " " + s);
  }
}

Output Question · Comparing Objects

Question 14: == or equals?

The Money class does not override equals. What does the program print?

class Money {
  int tl;
  Money(int tl) { this.tl = tl; }
}
// in main:
String a = "ab";
String b = new String("ab");
Money p = new Money(5);
Money q = new Money(5);
Money r = p;
System.out.println(a == b);
System.out.println(a.equals(b));
System.out.println(p.equals(q));
System.out.println(p.equals(r));
System.out.println(p.tl == q.tl);
Show answer
false
true
false
true
true
  • new String("ab") is a separate object: == compares references → false; String.equals compares content → true.
  • Since equals is not written in Money, the version from Object runs, and it behaves like ==: p.equals(q) → false, p.equals(r) → true (the same object).
  • p.tl == q.tl compares two ints → true.

Multiple Choice · Wrapper Classes

Question 15: The Integer Cache

What does the program print on the first line?

Integer a = 100, b = 100;
Integer c = 200, d = 200;
System.out.println((a == b) + " " + (c == d));
System.out.println(c.equals(d));
int e = 200;
System.out.println(c == e);

B: Integer a = 100 uses Integer.valueOf in autoboxing; values between −128 and 127 come from the cache as the same object: a == b → true. For 200 two separate objects are created: false. For content, c.equals(d) is used (true); in a comparison with an int such as c == e, the box is unboxed and the result is true.

Output Question · Records and enum

Question 16: enum Values

What does the program print? What would happen if Season.valueOf("Winter") were called?

enum Season { SPRING, SUMMER, AUTUMN, WINTER }
// in main:
Season m = Season.valueOf("AUTUMN");
Season[] t = Season.values();
System.out.println(m.ordinal() + " " + t.length);
System.out.println(m == Season.AUTUMN);
System.out.println(t[1]);
for (Season x : t) {
  if (x.ordinal() % 2 == 1) System.out.print(x + " ");
}
System.out.println();
Show answer
2 4
true
SUMMER
SUMMER WINTER 
  • ordinal() starts at 0: AUTUMN → 2; values() returns an array of four elements.
  • Every enum value is a single object; comparing with == is safe.
  • The ones with an odd ordinal: 1 (SUMMER) and 3 (WINTER).
  • valueOf looks for the name exactly (including case): for "Winter", IllegalArgumentException: No enum constant Season.Winter at run time.

Output Question · Inner Classes

Question 17: Three x's

The member inner class Inner accesses a private field of the outer class. What does the program print?

public class Outer {
  private int x = 10;
  class Inner {
    int x = 20;
    void show(int x) {
      System.out.println(x + " " + this.x
          + " " + Outer.this.x);
    }
  }
  static int x() { return 5; }
  public static void main(String[] args) {
    Outer o = new Outer();
    Outer.Inner i = o.new Inner();
    i.show(30);
    o.x = 15;
    i.show(x());
  }
}
Show answer
30 20 10
5 20 15
  • A plain x is the nearest declaration: the parameter. this.x is the field of the inner object, and Outer.this.x is the field of the outer object it is bound to.
  • o.new Inner(): a member inner class object is created bound to an outer object; after o.x = 15, the inner object sees the same outer object.
  • In the second call the argument is the 5 returned by the static method x().

Multiple Choice · Class Types and Design

Question 18: Singleton

The only object of the class Settings, whose constructor is private, is obtained with getInstance(). What does the program print?

class Settings {
  private static final Settings ONLY
      = new Settings();
  private int language = 1;
  private Settings() { }
  static Settings getInstance() { return ONLY; }
  void setLanguage(int l) { language = l; }
  int getLanguage() { return language; }
}
// in main:
Settings a = Settings.getInstance();
Settings b = Settings.getInstance();
a.setLanguage(2);
System.out.println(b.getLanguage()
    + " " + (a == b));

C: getInstance() returns the same static final object on every call; a and b are two references to the same object. a.setLanguage(2) changes the shared object: b.getLanguage() → 2, a == b → true. Writing new Settings() from another class does not compile: Settings() has private access in Settings.

The End

Chapter 4.1: Objects and Classes: Study Questions
Lecture slides: Chapter 4.1: Objects and Classes · Lecture notes
1 / 1 Sercan KÜLCÜ. All rights reserved.