Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Method Invocation

 
Deepa Krishnan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello all,

Non-static methods are invoked based on the run-type type of the object.How does a non static method behave with parameters of different objects? Can anybody explain based on this example.



class A1 {

void m1(A1 a) {
System.out.println("A1");
}

void m2() {
System.out.println("A1**");
}
}

class B1 extends A1{
void m1(B1 b) {
System.out.println("B1");
}

void m2() {
System.out.println("B1**");
}
}

class C1 extends A1{
void m1(C1 c) {
System.out.println("C1");
}
void m2() {
System.out.println("C1**");
}
}

class D {

public static void main(String[] args){

A1 a = new A1();
A1 b = new B1();
A1 c = new C1();
C1 cc = new C1();

a.m1(cc);
b.m1(cc);
c.m1(cc);

a.m2();
b.m2();
c.m2();
}
}

Thanks
Priya
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Polymorphisn depends on the actual type of the object the instance method is called on. However, the matching of method signatures to argument types is done at compile time based on the declared type of the reference.

In this case, the arguments used to call method m1() are all of type A1.

Method B1.m1(B1) cannot take an A1 argument because an A1 object might or might not actually be a B1 object. The same thing applies to method C1.m1(C1). So the only m1() method that can accept an A1 argument is A1.m1(A1).

Since only one of the overloaded m1() methods has a matching signature, polymorphism never happens.
 
ramaseshan T
Ranch Hand
Posts: 30
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


Let us try to think in the compiler way

//1 Do I have a matching function in class A1 for this? Yes.
void m1(A1 a) can accept object cc. (Since cc is an instance of class (c1) derived from A1 --> Displays A1

//2 Do I have a matching function in class B1 to accept object cc? Well. Though I don't have on my own, I inherited one function from A1
void m1(A1 a) which can take this argument cc.

//3 Above mentioned holds good here as appropriate to class C1

The point to note here is that compiler always looks for appropriate methods in the type of object it refers to and not the parent class A1..

//4 I have an appropriate function in class A1 to execute this statement.
//5 Above mentioned holds good for class B1

Output:

A1 A1 A1 A1** B1** C1**
Correct me if I am assuming something wrong...
 
Deepa Krishnan
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks for the reply.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic