Results 1 to 5 of 5
Thread: Can not find subclass method
- 11-24-2011, 11:25 AM #1
Member
- Join Date
- Nov 2011
- Posts
- 3
- Rep Power
- 0
Can not find subclass method
This code gives a compile error (Cannot find symbol method k() at sub.k())
and i need to know why this is. it does not give an error if MainClass has the exact same function k() (return type and arguments)
but i dont want that. is there any way to make this work?
Java Code:public class MainClass { public static void main(String[] args){ MainClass sub = new SubClass(); sub.k(); } } class SubClass extends MainClass { void k(){ System.out.println("1,2,3, test, test"); } }
- 11-24-2011, 12:19 PM #2
Member
- Join Date
- Nov 2011
- Location
- Budapest, Hungary
- Posts
- 5
- Rep Power
- 0
Re: Can not find subclass method
The trouble is, once you've used a MainClass reference to refer to your SubClass, you're stuck with only being able to call methods that exist in that particular form in MainClass.
You have two choices:
1. Use a reference of type SubClass (this makes sense!)
public class MainClass {
public static void main(String[] args){
SubClass sub = new SubClass();
sub.k();
}
}
class SubClass extends MainClass {
void k(){
System.out.println("1,2,3, test, test");
}
}
2. Downcast the MainClass variable to SubClass -- since it does, after all, refer to an object of type SubClass. But this is a bit crazy.
public class MainClass {
public static void main(String[] args){
MainClass sub = new SubClass();
((SubClass)sub).k();
}
}
class SubClass extends MainClass {
void k(){
System.out.println("1,2,3, test, test");
}
}
-
Re: Can not find subclass method
Better option: simply give MainClass a public void k() method. Why is this not a viable option if you want to treat MainClass variables as if they have this method?
- 11-24-2011, 05:17 PM #4
Member
- Join Date
- Nov 2011
- Posts
- 3
- Rep Power
- 0
Re: Can not find subclass method
for my program the easiest to do will be to add an empty method, I knew this worked but i wanted to know if i could avoid it. thank you for the help.
-
Re: Can not find subclass method
Similar Threads
-
HELP! can't find symbol-method
By Jack9333 in forum New To JavaReplies: 2Last Post: 03-04-2011, 01:48 AM -
subclass calling superclass method
By stackptr89 in forum New To JavaReplies: 10Last Post: 11-22-2010, 07:40 PM -
Using superclass fields in subclass method
By lonegreyride in forum New To JavaReplies: 12Last Post: 11-17-2010, 01:21 PM -
Subclass Overridden Method throws Exception Rule?
By hemanthjava in forum New To JavaReplies: 5Last Post: 05-14-2010, 02:20 PM -
Can't find method
By 01allenh in forum New To JavaReplies: 1Last Post: 03-25-2009, 07:46 PM


1Likes
LinkBack URL
About LinkBacks
Reply With Quote

Bookmarks