Results 1 to 5 of 5
- 10-17-2010, 04:34 AM #1
Member
- Join Date
- Oct 2010
- Posts
- 2
- Rep Power
- 0
Trying to call a method from sub class
Hi.. how can I call a method of a sub class from a reference of a super class. like this simple example
public class superClass{
//some stuff
}
public class subClass extends superClasss{
public void aMethodNotFromSuperClass() { //bla bla }
}
now in another file i make this:
superClass[] myArray = new superClass[10];
myArray[0] = new subClass();
myArray[0].aMethodNotFromSuperClass();
ok last line gives me error it cant find method. So is there any way to do it since im doing it wrong i guess??
-
You can cast the super class variable to a child class and call it that way, but you'd better be sure that the variable does in fact reference a child object!
Having said this, there are often other ways of solving such problems that diminish the risk of a bad cast, some using design patterns. Often you're better off here trying to describe what you're trying to achieve from a user experience viewpoint rather than from a code viewpoint.
- 10-17-2010, 05:28 AM #3
Member
- Join Date
- Oct 2010
- Posts
- 2
- Rep Power
- 0
ok fubarable will you give example how i can cast it?
basically.. i want to have several things i display info on screen, so i have 1 class they all inherit from. There are 3 sub classes that are differnt, and some have special methods the others dont use, so thoes methods are not in the super class.. now i want an array of thoes objects in my code and the array will use all 3 of the sub classes, so basically myArray[0] could be object of subClassA and myArray[1] could be object of subClassB but if i need to call a method only found in subClassB then i get the error i talk about. I think i did this in C++ before and had to use Static Cast but i dont know well Java so am lost i only know cast like normal cast which is not working:
double b = 2.5;
int a = (int) b;
some normal cast like that not working with my super class casting to sub class.
- 10-17-2010, 06:26 AM #4
Moderator
- Join Date
- Feb 2009
- Location
- New Zealand
- Posts
- 4,537
- Rep Power
- 11
Be careful with the parentheses:
Java Code:((subClass)myArray[0]).aMethodNotFromSuperClass();
- 10-17-2010, 07:08 AM #5
Similar Threads
-
how call from inner class(anonymous or not), a method of parent class?
By lse123 in forum AWT / SwingReplies: 2Last Post: 05-01-2010, 08:59 AM -
how to call higher level super class method?
By satheeshtech in forum Advanced JavaReplies: 2Last Post: 01-12-2010, 03:11 PM -
How to call a method from another class?
By jboy in forum New To JavaReplies: 8Last Post: 09-09-2009, 07:29 AM -
How to call a class within a method
By Manfizy in forum New To JavaReplies: 3Last Post: 03-19-2009, 12:34 PM -
[SOLVED] Call method from another class name
By antgaudi in forum New To JavaReplies: 3Last Post: 10-15-2008, 12:33 AM


LinkBack URL
About LinkBacks
Reply With Quote
Bookmarks