Win a copy of Clojure in Action this week in the Clojure forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Overloading

 
mi te
Greenhorn
Posts: 29
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 29
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm sorry. Please forget about the first question I asked. Still, please reply to the second question with kindness.
 
Ene Crus
Greenhorn
Posts: 8
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 142
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1704
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 15
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic