File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overloading Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overloading" Watch "Overloading" New topic
Author

Overloading

mi te
Greenhorn

Joined: Mar 09, 2006
Posts: 29
The first question is "Can I overload a method which is in super class from subclass?" (this probably isn't called overloading....well, I'd like to ask anyway.)

The second question is, well, please have a look at the code below.

class Super{
void meth(){System.out.println("supermeth");}
}

class Sub extends Super{
void meth(int i){System.out.println("submeth");}
}

class Data{
Super s = new Sub();
void meth(){
s.meth(3);
}
}

class Main{
public static void main(String args[]){
Data d = new Data();
d.meth();
}
}

Why does it not compile? Why doesn't s.meth(3); call the method of Sub class? s is holding a reference of Sub class isn't it? It is still searching through Super class. I don't understand this. Please someone explain this to me!
mi te
Greenhorn

Joined: Mar 09, 2006
Posts: 29
I'm sorry. Please forget about the first question I asked. Still, please reply to the second question with kindness.
Ene Crus
Greenhorn

Joined: Mar 19, 2006
Posts: 8
Hi there!

Hmm... Yup, it wont compile... Super class does not have a method by the signature in which it takes an integer as an argument. And when you upcast from Sub to Super, the instance created can only invoke the methods of Super, meth() as in the example. Only when you define the same method meth(int i) in Super class will you be able to to see the expected result...
S Thiyanesh
Ranch Hand

Joined: Mar 19, 2006
Posts: 142
Hi,
Jay Dc is right.
Have the stub in your super class with the method signature (meth(int i){}), to make the compiler happy.

Correct me if wrong
Kj Reddy
Ranch Hand

Joined: Sep 20, 2003
Posts: 1704
In you code you upcasting Sub object to Super object. But your Super object does not a method meth(int i), so the code do not compile.

What you did here is you overloaded a method meth() which is method in Super in child class, note that you are not overriding.

The above answers your first question too. You are allowed to overload a method which is in super class from subclass. But overloading a method in subclass from super class is not a good design practice.
ashish kediya
Greenhorn

Joined: Mar 02, 2006
Posts: 15
Hello Dear
at compile time object is not created
so it search for the method in refrence type
and could not found that method signatuer in
the super class n arise an error
ashish
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Overloading