Homework 51: What Is The Printout Of Running Class C

Homework 51 What Is The Printout Of Running The Class C Via The Comma

What is the printout of running the class C (via the command “java C”) in the code below (saved in C.java)? (And, is that what you expected?)

class A {

public A () {

System.out.println( "A's no-arg constructor is invoked" );

}

}

class B extends A {

}

public class C {

public static void main ( String [] args ) {

B b = new B();

}

}

When executing java C, the output will be:

A's no-arg constructor is invoked

This occurs because when creating an instance of B, Java implicitly calls the default constructor of its superclass A. Since class B does not define its own constructor, Java automatically generates a default constructor for B, which calls super(), invoking A’s no-argument constructor. The program's output matches the expectation because it shows the effect of the superclass constructor being invoked during object creation.

2. What problem do you expect to see if compiling the program below? What was the error(s), if any, actually produced?

class A {

public A ( int x ) {

}

}

class B extends A {

public B () {

}

}

public class C {

public static void main ( String [] args ) {

B b = new B();

}

}

Expected Problem:

In Java, if a superclass has only parameterized constructors, the subclass must explicitly call one of these constructors using super() with appropriate arguments in its constructor. Since class B's constructor does not invoke super(), Java attempts to insert a default super() call, which fails because class A does not have a no-argument constructor. This results in a compilation error.

Actual Error:

The compiler typically reports: error: constructor A in class A cannot be applied to given types; required: int; found: no arguments. The fix involves adding an explicit call to super(x) in class B's constructor with an integer argument, e.g., super(0);.

3. Which of the follow statements are true? Which are false? Explain why.

  • A subclass is a subset of a superclass. False. A subclass is a specialized version or extension of a superclass, not a subset. It inherits properties and behaviors, but it can also add new features.
  • When invoking a constructor from a subclass, its superclass's no-arg constructor is always invoked. False. If the subclass's constructor explicitly calls a different superclass constructor using super(args), then that constructor is invoked instead. If no super() call is specified, Java defaults to invoking the no-arg constructor of the superclass, which may be absent, leading to a compile-time error.
  • You can override a private method defined in a superclass. False. Private methods are not accessible outside their class, and thus cannot be overridden. They can be hidden (shadowed), but not overridden.
  • You can override a static method defined in a superclass. False. Static methods are associated with classes, not instances, and overriding static methods results in method hiding, not polymorphic overriding. The static method in the subclass hides the superclass's static method.

4. What is the benefit of using the @Override annotation?

The @Override annotation indicates that a method is intended to override a method declared in a superclass. Its primary benefit is to enable compile-time checking: if the annotated method does not correctly override a method in the superclass (e.g., due to a typo, incorrect signature, or mismatched parameters), the compiler will generate an error. This helps prevent bugs caused by unintentionally not overriding methods as intended and improves code clarity by explicitly signaling override intentions to developers.

5. Show the output of the following program:

public class Test {

public static void main ( String [] args ) {

A a = new A( 3 );

}

}

class A extends B {

public A ( int t ) {

System.out.println( "A's constructor is invoked" );

}

}

class B {

public B () {

System.out.println( "B's constructor is invoked" );

}

}

The output will be:

 Sabout

Explanation:

When executing new A(3), Java first calls the constructor of class A. Since class A extends B and it does not explicitly call super(), Java implicitly calls super(). This invokes B's no-argument constructor, printing "B's constructor is invoked", followed by A’s constructor printing "A's constructor is invoked".

Note: The output should be specifying the order, so more precisely, it is:

B's constructor is invoked

A's constructor is invoked

Is the no-arg constructor of Object invoked?

Yes. When new A(3) is invoked, the constructor chain includes Object's constructor (the topmost class). However, since Object's constructor is empty, typically no output is produced from it, but it is invoked implicitly.

6. Indicate true or false for the follow statements:

  • You can always successfully cast an instance of a subclass to a superclass. True. Upcasting (casting subclass to superclass) is always safe and implicit in Java.
  • You can always successfully cast an instance of a superclass to a subclass. False. Downcasting requires the actual object to be an instance of the subclass; otherwise, a ClassCastException occurs at runtime.

7. What's wrong with the following code?

public class Test {

public static void main ( String [] args ) {

Object fruit = new Fruit();

Object apple = (Apple) fruit;

}

}

class Apple extends Fruit { }

class Fruit { }

Issue:

While the code compiles, it causes a runtime ClassCastException if the object referenced by fruit is not actually an Apple. In this case, since fruit is a Fruit object, casting it to Apple is invalid and throws an exception at runtime. This illustrates the danger of downcasting without type checking.

8. When overriding the equals method, a common mistake is mistyping its signature in the subclass. For example, the equals method is incorrectly written as equals(Circle circle). It should be written as equals(Object circle). Show the output of running class Test using the Circle class first from (a), then from (b). Explain the output. Also, try adding the “@Override” annotation to the equals method in both cases and explain the results.

Code (a)

class Circle {

double radius;

public boolean equals ( Circle circle ) {

return this.radius == circle.radius;

}

}

Code (b)

class Circle {

double radius;

@Override

public boolean equals ( Object circle ) {

if (!(circle instanceof Circle))

return false;

return this.radius == ((Circle) circle).radius;

}

}

Test Class

public class Test {

public static void main ( String [] args ) {

Object circle1 = new Circle();

Object circle2 = new Circle();

System.out.println( circle1.equals( circle2 ) );

}

}

Output with (a):

Since equals takes a Circle parameter, but the method is invoked via Object.equals() with Object parameters, the overridden method in (a) is not recognized as overriding the Object's equals. Instead, it hides it, but the default Object's equals method is invoked, which compares references, so output is true or false depending on object references. Typically, it outputs false because they are different objects.

Output with (b):

The method correctly overrides equals(Object). When adding @Override, the compiler confirms the override is successful. The output is false, as the two circle objects are distinct instances.

Summary:

Using the wrong method signature prevents proper overriding. Adding @Override helps catch such errors during compilation, ensuring correct method override behavior.

9. How would you prevent a class from being extended? How would you prevent a method from being overridden?

To prevent a class from being extended, declare it as final. For example: public final class MyClass { ... }.A final class cannot be subclassed.

To prevent a method from being overridden, declare it as final within the class. For example: public final void myMethod() { ... }. A final method cannot be overridden in subclasses.

10. Which of the following classes define legal abstract classes?

  • A:
    class A {
    

    abstract void unfinished() { }

    }

    False; cannot have method body in an abstract method declaration without abstract.
  • B:
    public class abstract A {
    

    abstract void unfinished();

    }

    False; cannot declare a class as both public and class without abstract.
  • C:
    class A {
    

    abstract void unfinished();

    }

    True; proper abstract method declaration in a class.
  • D:
    abstract class A {
    

    protected void unfinished();

    }

    False; abstract method must have no body, so missing braces and syntax error.
  • E:
    abstract class A {
    

    abstract void unfinished();

    }

    True; correct abstract class with an abstract method.
  • F:
    class A {
    

    abstract int unfinished();

    }

    False; an abstract method must be declared in an abstract class, but class A is not declared abstract.

11. Suppose A is an interface. Can you create an instance using “new A()”?

No. In Java, interfaces cannot be instantiated directly because they are abstract by nature. You must implement the interface in a class, instantiate that class, and assign it to an interface reference.

12. Which of the following (if any) is a correct interface declaration?

  • A:
    interface A {
    

    void print() { }

    }

    Incorrect; cannot have method bodies in interfaces prior to Java 8 unless default or static methods, but in the default context, this syntax is invalid.
  • B:
    abstract interface A extends I1, I2 {
    

    abstract void print() { }

    }

    Incorrect; interface cannot be declared with abstract keyword explicitly (since interfaces are inherently abstract). Also, method body in interface is invalid unless default/static. Also, 'abstract' is redundant here.
  • C:
    abstract interface A {
    

    print();

    }

    Incorrect; 'abstract' keyword should not be used before interface declaration.
  • D:
    interface A {
    

    void print();

    }

    Correct; interface with an abstract method declaration, valid in Java.

Additional: How to create a Date and display current time, manipulate Lists, and work with Calendar and java.time API

To create a Date object representing the current time, use:

java.util.Date now = new java.util.Date();.

To display the current time, simply print the Date object:

System.out.println(now);, which outputs the current date and time in default format.

Creating an ArrayList for storing doubles:

ArrayList<Double> list = new ArrayList<>();

Appending an object to a List:

list.add(someObject);

Inserting an object at the beginning of a List:

list.add(0, someObject);

Finding the number of objects in a List:

list.size();

Removing a specific object:

list.remove(someObject);

Removing the last object from the List:

list.remove(list.size() - 1);

Checking whether a List contains an object:

list.contains(someObject);

Retrieving an object at a specific index:

list.get(index);

To remove all elements (assuming elements are known or equal), you could use:

list.clear(); or iterate and remove as necessary.

For creating a Calendar object representing the current moment:

Calendar cal = Calendar.getInstance();

Getting year, month, date, hour, minute, and second from a Calendar object:

- year: cal.get(Calendar.YEAR);

- month: cal.get(Calendar.MONTH); (zero-based)

- date: cal.get(Calendar.DAY_OF_MONTH);

- hour: cal.get(Calendar.HOUR_OF_DAY);

- minute: cal.get(Calendar.MINUTE);

- second: cal.get(Calendar.SECOND);

Using java.time API, to add one month to a LocalDate object:

localDate.plusMonths(1);.

To create a LocalDate object that represents the last Friday of the current month, you can use TemporalAdjusters:

LocalDate.now().with(TemporalAdjusters.lastInMonth(DayOfWeek.FRIDAY));