简体   繁体   中英

If I have a method in a subclass that asks for an object of the super class, how do i distinguish both?

What I mean by this is, if I have A obj1 = new B(); A obj2 = new B(); A obj1 = new B(); A obj2 = new B(); I want to know how to call the same method for both objects, and also want to know how to know which object is calling the method and when:

For example, lets say my class hierarchy looks something like this:

abstract class A {
    public void method_1() {
        //Do something
    }
}

class B extends A {
    public boolean method_2(A obj) { 
        //Do something
    }
}

If I where to do obj1.method_2(obj2); How do I, inside method_2() , when I code it so both obj1 and obj2 call method_1() , distinguish which obj is calling the method?

I hope my question was clear enough. I'm sorry in advance if my English wasn't understandable enough.

obj1 which is instance of B but references class A, won't have access to method_2 So you need to cast like this

((B) obj1).method_2(obj2);

or you can change the reference to B instead of A

B obj1 = new B();

Base reference can't call the child's method.

public class Main {

    public static void main(String arg[] ) {
        A obj1 = new A() {};
        A obj2 = new B();
        B obj3 = new B();

        obj1.method_1("1 "+obj1.getClass());
        obj2.method_1("2 "+obj2.getClass());

        obj3.method_1("3 "+obj3.getClass());

        obj3.method_2(obj1);

        obj3.method_2(obj2);
    }

}


abstract class A {
    public void method_1(String className) {//Do something
        System.out.println("A.method_1() called by "+className);
    }
}


class B extends A {
    public boolean method_2(A obj) {//Do something
        super.method_1("4 "+obj.getClass());
        obj.method_1("5 "+obj.getClass());

        return true;
    }
}

You can NOT create an object of class A as its abstract class. However you can create object of B and pass it in place of A in method_2(). When you call method_1() inside method_2(), you are still calling it through object of class B. Here is the test program I could write based on my understanding of your question -

public class App {

    public static void main(String[] args) {

        B b = new B();
        B b2 = new B();
        b.method_2(b2); //Or
        //b.method_2((A)b2);

    }

}

abstract class A {
    public void method_1() {
        System.out.println("In method_1 = " + this.getClass());

    }
}

class B extends  A {
    public boolean method_2(A a) {
        System.out.println("In method_2 = " + this.getClass());
        a.method_1();
        return false;

    }
}

The result is that both methods are called by object of class B. You can user getSuperClass() method to get superclass name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM