Overriding and overloading together

Hi all,i've a qn on overloading and over-riding combined.
Consider the following program.
class base {
int i;
base(int val) { i = val; }
void f(int i) { System.out.println("base int"); } // <1> case1
void f(double d) { System.out.println("base double"); } //case2
class sub extends base {
int j;
sub(int val1, int val2) { super(val1); j = val2; }
void f(int i) { System.out.println("sub int"); } // <2> //case3
void f(double d) { System.out.println("sub double"); } //case4
class Test {
public static void main(String argv[]) {
base a = new base(1);
sub s = new sub(1,2);
base b = s;
a.f(1);
a.f(1.2);
s.f(1);
s.f(1.2);
b.f(1);
b.f(1.2);
when i comment case1 follwoing is printed
base double
base double
sub int
sub double
sub double
sub double
apparently the reason being, when i override the overloaded function, the over-riding will hide all the variants of the member function and not just the one which i overrode.
Line 5 - Here the subtle issue is that we are overriding already overloaded
function. Case2 and case3 are overloaded (in base/sub classes) and case4
overrides case2. Due to this , the overriding hides all the overloaded
variants of that member function and hence case2/case3 are hidden. So due
to dynamic binding and hiding of the overloaded (case3) , sub's double is
called. Also since sub's int is not availble, co-ercion takes place too. IS THIS REASONING CORRECT??
Also,what happens if i uncomment case1 and comment case3??
Where can i find more information on this??
Any help is highly appreciated
Regards

Then what will happen if i uncomment case1 and comment case3?Did you try it?
base int
base double
base int
sub double
base int
sub doubleIt is the difference between early and late binding.
Overloaded methods are bound early.
Overridden methods are bound late.
To reiterate,
Determining which of the overloaded methods to call is done when the class is compiled[], based on the compile time type information.
Determining which overridden version of that method to call is done at [b]runtime.
Even if a subclass DOES have a more appropriate overloaded method to call at runtime, that method can not get used. This was demonstrated when you commented out case1. The most appropriate method it found in the base class took a float. It knew nothing (at that time) about the overloaded version in the subclass.
So we know the signature of the method we are going to call before we run the program.
At runtime it looks at the actual type of the object that it has, and calls the version most lately declared in the object's hierarchy - ie this resolves the overriding.
So explaining the results above:
It detemines at compile time which version of the overloaded methods it will call.
Because both are available in the base class, it will call
f(int)
f(double)
f(int)
f(double)
f(int)
f(double)
At RUNTIME, when you call it
- the first object is of type base, and thus calls the int and double methods of base
- the second object is of type sub. But it doesn't override the int version of the method, so base's implementation is used. It DOES override the float version, so you get its implementation there.
- same result for the third object.
Hope this clears things up,
cheers,
evnafets

Similar Messages

  • About method overriding and overloading

    Hi,
    What we need method overriding and overloading
    What is significance of it
    regards
    Amar

    I've read a few articles lately about people whose senses and catagories seem to "leak"
    from one to another. For example
    * Monday is red, Tuesday is yellow, etc..
    * G is red, E flat is yellow, etc...
    * Red is sour, yellow is bitter, etc...
    With that in mind...
    Overriding is spicey (garam masala), overloading is bitter (top note of asafoetida).

  • Question about overriding and overload

    Below is a super class named Animal and subclass named Horse
    public class Animal {
    public void eat() {
    System.out.println("Generic Animal Eating Generically");
    public class Horse extends Animal {
    public void eat() {
    System.out.println("Horse eating hay ");
    public void eat(String s) {
    System.out.println("Horse eating " + s);
    public class Test {
    public static void main ( strin []agrs) {
    Animal ah2 = new Horse();
    ah2.eat("Carrots");
    At the bold line, why can not polymorphism work here.
    Can anyone explain it to me pls.
    Thanks

    800239 wrote:
    Below is a super class named Animal and subclass named Horse
    public class Animal {
    public void eat() {
    System.out.println("Generic Animal Eating Generically");
    public class Horse extends Animal {
    public void eat() {
    System.out.println("Horse eating hay ");
    public void eat(String s) {
    System.out.println("Horse eating " + s);
    public class Test {
    public static void main ( strin []agrs) {
    Animal ah2 = new Horse();
    *ah2.eat("Carrots");*
    }At the bold line, why can not polymorphism work here.
    Can anyone explain it to me pls.
    ThanksThe variable ah2 is declared as a reference of type Animal. That means we can only call methods that exist and are accessible in Animal. The compiler doesn't know or care that at runtime the Animal reference variable points to a Horse object. All that it sees is that ah2 is of type Animal.
    The kind of polymorphism where that does matter is when a child class overrides (not overloads) a non-static, non-final, non-private parent method with the exact same signature.

  • Overriding and Overloading

    Hi,
    I'm new to abstract Java world.
    If I compare Overide and Overload,
    Does it just mean
    OVERIDE superclass and subclass having same method name with different functions?
    But OVERLOAD is having more than 1 method with the same name but with different functions?
    Thanks,

    Generally you're right. In specification there is "method signature" used to distingush it.
    overide: exactly same signature but different implementation in subclas
    overload: same name but different signature, means: list of arguments, thrown exception

  • About overriding and overloading - Advanced Topic

    Please look at this thread
    http://forum.java.sun.com/thread.jsp?forum=31&thread=159240
    Someone posted a code snippet that I can't fully explain, perhaps some Java Guru can answer!

    This is the program:
    The question is why the compiler error in the indicated line but not when upcating b to Homer.
    <code>
    class Homer {
         float doh(float f) {
              System.out.println("doh(float)");
              return 1.0f;
         char doh(char c) {
              System.out.println("doh(string)");
              return 'd';
    class Bart extends Homer {
         float doh(float f) {
              System.out.println("doh(float)");
         return 1.0f;
    class Hide {
         public static void main(String[] args) {
              Bart b = new Bart();
              b.doh('x');//compiler error in this line
              b.doh(1);
              b.doh(1.0f);
    </code>
    I looked for an answer in the Java Language Specification and I found the section 15.12.2.2
    I will try to sum up in the following:
    Steps performed by the compiler to spawn the symbolic reference for a given method invocation:
    1) It finds out which class or interface looked for the method declaration.
    In the example b.doh('x'); is the type given of b, that is Bart.
    2) Looks for the methods that are both applicable and accesible in the methods declared and inherited in that type.
    A method declaration is applicable to a method invocation if they have the same number of parameters, and, the types of the arguments in the declaration are the same or can be converted via a widenning convertion to those of the declaration.
    Whether a method declaration is accessible to a expression of method invocation depends on the modifiers specified in the declaration and where the invocation occurs.
    If there are several methods declaration both applicable and accessible the one more specific is chosen. If no more specific method exist, the compiler generates an error.
    This how to find out which method is more specific:
    Let T be the class where a method m is declared, and let U be another class where a method called as well m is declared. Both have the same number of parameters because they are applicable, but they have different types in the argument list. If it happens that T is a subclass of (or the same as) U, and, all the parameters types in the m declared in T can be converted via widenning convertion to those in the m declared in U (or are the same); the m in T is more specific than the m in U.
    3) The checks described in the section 15.2.3 in the JLS are performed. They do not apply in our example.
    Back to the example, the compiler finds two applicable and accessible methods in Bart:
    float doh(float f)      declared in Bart
    char doh(char c)     declared in Homer     
    The last one inhertited from Homer.
    So which is the more specific? let�s see first if doh declared in Bart is more specific than doh declared in Homer: Bart is a subclass of Homer, but float is not of the same type nor widenning convertible to char . Now, if doh in Homer is more specific than doh in Bart: well, Homer is not the same nor widenning convertible to bart. So there is no a more specific method and the compiler complains.
    If you apply these rules to b upcasted to Homer doh(char) is more specific. The same happens if doh(char) is added to Bart.

  • Can I run Apple TV 1 and 2 together on the same iTunes account and on the same tv with two hdmi slots?

    Can I run Apple TV 1 and 2 together on the same iTunes account and on the same tv with two hdmi slots?

    Yes.
    Captfred

  • I have a ipod shuffle synced to a desktop (ver 9), I have a new laptop and downloaded itunes (ver 10.7).  When i plug the ipod in the new laptop it wants to delete my songs. How do i use my new alptop and ipod together?

    I have a ipod shuffle synced to a desktop (ver 9), I have a new laptop and downloaded itunes (ver 10.7).  When i plug the ipod in the new laptop it wants to delete my songs. How do i use my new alptop and ipod together?

    Your iPod is designed to sync with only one iTunes library at a time.  It will recognize the iTunes library on the PC as a new library.  If you sync the iPod with this new library, all content will be erased from the iPod and replaced with what is in the new library.  So what you will want to do is copy everything from the iPod to your new iTunes library on your PC first.
    See this excellent user tip from another forum member turingtest2 outlining the different methods and software available to help you copy content from your iPod back to your PC and into iTunes.
    Recovering your iTunes library from your iPod or iOS device
    B-rock

  • HT1277 I have changed my email account on my computer to imap and 993 but now I'm not receiving any emails. I was originally trying to sinc my ipad and iphone and computer together so when I delete an email it will all delete together. What is the best wa

    I need help to update my email and also to sinc my computer, iphone and ipad together so when I delete my emails they will all disappear together. I got the iphone and ipad to work but cant seem to get the computer to work.

    E-mail provider?
    Troubleshooting sending and receiving email messages

  • How can I run a vga monitor and projector together on my Mac Pro 15"??

    How can I run a vga monitor and projector together on my Mac Pro OSX 15"?

    You can upgrade to Snow Leopard, Lion or Mountain Lion (coming next month), but you need Snow Leopard to upgrade to Lion or Mountain Lion. Check this web to know how to add memory to your computer and the memory that it supports (probably, 3 GB).

  • How can I create a client console and work together with the Cache Server?

    How can I edit the following Cache-Server.cmd file to create a client console and work together with the Cache Server?
    The following is the cache server file: contacts-cache-server.cmd
    @echo off
    setlocal
    if (%COHERENCE_HOME%)==() (
    set COHERENCE_HOME=c:\coherence
    set CONFIG=C:\home\oracle\coherence\Contacts
    set COH_OPTS=%COH_OPTS% -server -cp %COHERENCE_HOME%\lib\coherence.jar;C:\home\oracle\
    coherence\Contacts;C:\home\oracle\coherence\Contacts\classes;
    set COH_OPTS=%COH_OPTS% -Dtangosol.coherence.cacheconfig=%CONFIG%\contacts-cache-config.xml
    java %COH_OPTS% -Xms1g -Xmx1g -Xloggc: com.tangosol.net.DefaultCacheServer %2 %3 %4 %5 %6 %7
    :exitEdited by: junez on 23-Oct-2009 09:20

    Hi
    To run the console, change DefaultCacheServer to CacheFactory
    Paul

  • TS4006 Hi I am having trouble updating my apps I have tried one at a time and all together but they just will not load any ideas would be appreciated

    Hi, I am having trouble updating my apps, I have tried one at time and all together but they just keep on whirring away and nothing happens! any ideas woud be appreciated.

    Suggest you update all these apps on iTune (computer) and sync them to your iPad.

  • How to use external hard drive and iTunes together?

    how to use external hard drive and iTunes together?

    Yes I did get to that part.... I went trough external to retrive itunes folder... When I selected the folder, it said that it was locked, choose another folder... I then went to my external again to my itunes folder and and used command I to see if folder was locked and it wasn't.... it was suggested on another forum to reboot.. which I did and still same problem... All I want to do is link my external hard drive that has my itunes playlist from another Mac to my new one.. and to also use the external as the main source for adding new songs to my playlist...

  • Why can't Adobe Premiere Pro CC 2014 Time remap Audio and Video together?

    In case you didn't notice, my question is WHY.  I don't know why Premiere Pro can't do this.  From what I understand at the moment, the only way to time-remap audio in any way shape or form using Adobe software is through Adobe After Effects, which my computer has absolutely no chance of running ever.  I know how to do regular stretching of audio in both Audition and Premiere Pro, but apparently I can't time-remap audio using either of these programs.
    So why can't Adobe Premiere Pro time remap audio along with the video?  What's the reason that it can't?  It's a massive disappointment and would be very impressive to see accomplished in the future.  If it's possible to time remap audio and video together in After Effects, that's great and all, except for the fact that I can't use that program.  Why can't it be done in Premiere Pro and will it ever be possible in Premiere Pro?
    Also, will time remapping audio become possible in Audition someday?

    That sounds like a great idea.  File a Feature Request:
    Adobe - Feature Request/Bug Report Form

  • Hi... I am looking for an inexpensive app for my macbook pro that I can put pictures and videos together into a slideshow with captions and music WITHOUT a watermark and that also will burn the slideshow to a DVD in its own app. Help?

    Hi... I am looking for an inexpensive app for my macbook pro that I can put pictures and videos together into a slideshow with captions and music WITHOUT a watermark and that also will burn the slideshow to a DVD in its own app. Help?

    The issue with the A1400 is that like most economy compact cameras, they will not have very fast focus times in indoor lighting situations. Many people have gone to entry level DSLR's (Canon T3i) or micro 4/3 cameras. They are fairly expensive, but a late model refurbished T3i can sometimes be found with a kit lens for about $300.00. With Auto and scene modes, as well as full manual modes, these are very versatile cameras that focus very quickly, even in lower lighting situations. Canon is not really into the micro 4/3 cameras, instead they are focusing on the new G7x and G1x cameras, which are way out of your price range. The A720 is still available used at some places such as KEH camera, but you'll need to check often as their stock changes constantly. Obviously the DSLR's don't use AA batteries, but the T3i is good for about 600 photos (or more) per charge.
    My refurbished DSLR was practically brand new condition when I got it. I could not find any sign of wear at all, so I feel they are a real bargain. These are rugged cameras that are made to last. The A1400 is a $99.00 camera, so it's not intended for heavy usage, plus the image quality of a DSLR (even entry level) is far better than the A1400. That would be my recommendation.
    Steve M.

  • How to keep form field and label together?

    In InDesign Creative Cloud (ID CC), I need to create a 20 page form (a type of questionnaire). As a prelude to doing this, I created a one page form. I am trying to keep labels (text) and fields together, so that if I add a question in the middle of the form, everything else moves down and stays in the correct alignment and relationship. Here is what I tried.
    Option 1: Anchored Fields. I created fields on a "fields" layer and labels on a "text" layer. The text layer generally had tables to help me see where fields should be placed. However, to keep fields and text in the same relationship on the page, I anchored the field to the text. Hoewever, this has the effect of moving the field object into the same layer as the text. When I tried to use the Articles panel to put the fields in correct tab order, I discovered that only fields (unanchored) that were in the forms layer could be dragged into the Articles panel; anchored fields (now in the text layer) could not be dragged into the Articles panel. Why?
    I know that I could also use the Object / Interactive / Set Tabs Order command, but I wanted to use Articles to see how that works.
    In this approach, I also could not figure out how to put underline the text form field
    Option 2: Tabs and Character Styles. I used character styles for underlining by not using tables, but using paragraphs and tabs to align where the fields should be. I applied a character style to a right-justified tab to get the underline. However, using this option, whenever I add a new question (field + label or instruction) in the middle of the form, everything else down on the page goes out of alignment.
    What recommendations do other form designers have? I have been trying to think of how IRS has "dense" or "complex" forms, and how these might be designed in InDesign CC. in order to apply similar techniques to my form design.
    I am running on a Mac, OS X 10.8.4, InDesign CC.

    Unless I am gravely mistaken, isnt this what you want?
    for (int i = 0; i < folderList.size(); i++) {
       String folder = (String) folderList.get(i);
        System.out.println("Folder: " + folder);
        System.out.println ("Messages: " + folderMap.get (folder));
    }

Maybe you are looking for

  • Incorrect Display of Totals (Urgent ! Plz Assist)

    Hi everyone,   Please help me out as this is very urgent at the moment.    When I display    PLANT    STORAGE LOC    WAREHOUSE NO    PROFIT CENTRE    MATERIAL    No of Bins -> 7338.6821235    When I display the same report just with    PROFIT CENTRE

  • Web service client stubs generation

    Hi, I try to generated model for WebDynpro application based on Web service (deprecated). WSDL file is valid. Stub classes generation is completed with compilation error. I found that the generator builds strange method for CMapLayerField complex typ

  • Secure Empty Trash Problem After Installing Security Update 2010-005

    Some items in trash were locked, selected option to remove all items and nothing was deleted. Rebooted twice, no change. Unsecure empty trash works fine. Any ideas?

  • Installation Error for ECC6.0 IDES

    I'v got the error logs as follow at the configure the CAF step: INFO 2009-11-02 00:25:12 Execution of the command "C:\j2sdk1.4.2_18\bin\java.exe -classpath C:/usr/sap/NW4/DVEBMGS00/j2ee/cluster/server0/apps/sap.com/tclmctcutilbasic_ear/servlet_jsp/ct

  • I am having problems getting this code to work.

    public class Polar {      public static void main(String[] args) {           int angle;           int distance;           int x1;           int y1;      public Polar (int angle, int distance, int x1, int y1) {           this.angle = angle;