| Author |
Polymorphic Method Call
|
Mike Cutter
Ranch Hand
Joined: Jun 09, 2002
Posts: 49
|
|
I am taking a Java class and we are covering polymorphism.
I have to utilize the given code in my assignment:
I put all this into one big public class. When I complied it, I get the following error:
<identifier> expected
x.a2();
How do I get this polymorphic method call x.a2(); to compile without errors?
Thanks,
Mike
|
 |
Jesper de Jong
Java Cowboy
Bartender
Joined: Aug 16, 2005
Posts: 12929
|
|
What does the exact code that you are trying to compile look like?
Note that you cannot put statements like x.a2(); at class level - statements have to be inside a method. So, something like this is not going to work:
You need to put the statement inside a method, for example the main() method:
|
Java Beginners FAQ - JavaRanch SCJP FAQ - The Java Tutorial - Java SE 7 API documentation
Scala Notes - My blog about Scala
|
 |
Mike Cutter
Ranch Hand
Joined: Jun 09, 2002
Posts: 49
|
|
I put the x.a2(); in the main() method.
I now get this error:
non-static variable this cannot be referenced from a static context
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
|
x is a non-static field. To access it from any static method you need an instance of C. So either create a new C and use it's x field, or make x static.
|
SCJP 1.4 - SCJP 6 - SCWCD 5
How To Ask Questions How To Answer Questions
|
 |
Mike Cutter
Ranch Hand
Joined: Jun 09, 2002
Posts: 49
|
|
I tried the following code:
I get the following compilation errors:
non-static variable x cannot be referenced from a static context
x.a2();
non-static variable z cannot be referenced from a static context
z.a2();
non-static variable z cannot be referenced from a static context
z.a1();
non-static variable x cannot be referenced from a static context
x.a1();
I'll admit I am pretty lost on why the syntax is wrong and the logic is not making sense.
|
 |
Rob Spoor
Sheriff
Joined: Oct 27, 2005
Posts: 19216
|
|
x, y and z are all declared inside the class and are therefore non-static instance fields. Notice the word "instance" - you need an instance of class MyClass to access them.
There are three ways to solve this:
1) create an instance of MyClass (let's call it "my"), then use that to access them ("my.x.a2()").
2) make them static; simply put the static keyword in front of their declarations.
3) move them inside the main method.
|
 |
 |
|
|
subject: Polymorphic Method Call
|
|
|