Java Example Pool Questions

Asked 1 weeks ago, Updated 1 weeks ago, 1 views

class X { 
    public void f( ) { System.out.print("1"); }
    public static void g() { System.out.print("2"); }
}

class Y extends X{
    public void f( ) { System.out.print("3"); }
}

class Z extends Y {
    public static void g( ) { System.out.print("4"); }
}


public class num23 {

    public static void main(String args[]) {
        X obj = new Z( );
        obj.f( );
        obj.g( );
    }
}

obj.f(): Call f( ) in class Z, call f( ) in class parent and output 3

obj.g(): Call g( ) of class Z and output 4

Output result: 34

I solved it in the same format as above, and the answer was 32.

If so

java

2022-09-20 10:17

1 Answers

The answer is 32. If you run the code as it is, "3" + "2" will be printed.

When Xobj = newZ(), obj is assigned an instance of the upcasting Z class as X.

And the methods of Z and Y are 'covered' due to upcasting.

Y.f() is hidden, so you might think that you cannot call. However, in this inheritance, X.f() only serves to guide Y.f() (so that it can be called). The actual invocation is Y.f() that overrides X.f(). (If you ask why this is happening...) Java is just like that 🤭)

So the actual output is "3" and this is what happens when you fix the code:

class Y extends X {

    @Override // This annotation has no functional elements and just acts like a comment.
    public void f( ) { 
        System.out.print("3"); 
    }
}

For example, if you have this class:

public class Wahappen {

    @Override
    public String toString() {
        return "Wa happening here";
    }
}

Let's upcast with Object which is a super class of all classes:

Object obj2 = new Wahappen();
System.out.println(obj2.toString()); // "Wa happening here"

Where obj2.toString() points to Object.toString() but what actually runs is Wahappen.toString().

Static methods are excluded from inheritance. In addition, X.g() is a static method and must be called static. Therefore, calling through the instance is the wrong way, as shown below:

X obj = new Z( );
obj.g();

However, since Java corrects it, there is no error. Because it automatically changes like below:

X obj = new Z( );
//obj.g();
X.g();

I am attaching another example below:

public class StaticMethodsHeritance {
    public static void main(String[] args) {
        Parent instance = new Child();
        instance.print(); // Child output
        instance.staticPrint(); // Parent Output
    }
}

class Parent {
    public void print() {
        System.out.println("Parent");
    }

    public static void staticPrint() {
        System.out.println("Parent");
    }
}

class Child extends Parent {
    public void print() {
        System.out.println("Child");
    }

    public static void staticPrint() {
        System.out.println("Child");
    }
}

I'm not sure what dynamic binding means. 🤔

- End-


2022-09-20 10:17

If you have any answers or tips


© 2022 pinfo. All rights reserved.