Method override problems

I am new to Java programming and this is likely a trivial problem, but I have been unable to find an answer after a few hours in books and on the Web.
I have created two subclasses of a class, and overridden a public method (the same method) in each of the subclasses. At runtime however, all calls to this method from an instance of the superclass or either subclass results in the same method; i.e. the override in one subclass is overriding the other subclass and the superclass. Why is the scope of this override so large, and how do I fix this?
Thanks,
~Jon Hurst

I think there must be something wrong in the way the instance is being created. Anyway try running the sample below and you will see that it works the way it is expected to.
Hope this helps.
regards
manalar
<code>
public class SuperClass{
public void display(){
System.out.println("display in super class");
import SuperClass;
public class AnotherClass{
public AnotherClass(){
          SuperClass sc = new SuperClass();
          sc.display();
          SubClass1 sb1 = new SubClass1();
          sb1.display();
          SubClass2 sb2 = new SubClass2();
sb2.display();
public void display(){
System.out.println("display in AnotherClass");
private class SubClass1 extends SuperClass{
public void display(){
System.out.println("display in SubClass1");
private class SubClass2 extends SuperClass{
public void display(){
System.out.println("display in SubClass2");
public static void main(String args[]){
AnotherClass ac = new AnotherClass();
ac.display();
</code>

Similar Messages

  • Abstract Method Overriding Problem

    I have an abstract class called "Employee" with an abstract method called "ReturnBasicInfo()" defined.
    I have two subclasses, SalariedEmployee and HourlyEmployee, and each has their own version of ReturnBasicInfo(). The compiler is not letting me do this, however, and I have no idea why.
    I keep getting this error:
    SalariedEmployee.java:6: SalariedEmployee is not abstract and does not override
    abstract method returnBasicInfo() in Employee.The abstract method signature is this:
    public abstract String returnBasicInfo(Employee e);Any idea why this might be happening? I have another abstract method called toVector() that's overriden in the subclasses and that one works fine, so I'm stumped on this. The only difference between the two is that this method takes arguments and the other doesn't. Is that why it can't be overriden?
    Thanks in advance for any help!

    "...In the instructor's example code, he actually
    overrode toString with this method. I thought I might
    be using the real toString(), though, so that's why I
    changed the name to returnBasicInfo(). I didn't end up
    using toString(), though. Maybe I ought to go back to
    calling it toString()..."
    Yes, this SHOULD be overridden in toString(). Do go
    back to it.
    The "real" toString()? Do you mean the default
    version in java.lang.Object, the one that just prints
    out the object reference when it's called?
    Hmm, I guess. I got confused because I'm swapping between String and double values a lot. Taking in an entered number as a String and converting it to a double.
    I think I originally confused toString() with String.valueOf().
    I wouldn't have getYearlySalary() for SalariedEmployee
    and getHourlySalary() for HourlyEmployee. That
    defeats the purpose of polymorphism and dynamic
    typing. Yes, but I do have one polymorphic method --pay(). Each Employee is paid a different way. The one method we were supposed to be able to call on all Employees is just pay(). There is one version of pay() for HourlyEmployees that uses gethourly_rate() and gethours_worked() to get hourly rate and hours worked. The other version of pay() in SalariedEmployees takes in their yearly salary and number of pay periods worked.
    Better to have a getSalary() method in your
    Employee interface and let each subclass implement it
    the way they want to. SalariedEmployee will return
    their yearly salary, HourlyEmployee will return
    hourlySalary*hoursWorkedOK, that's one idea.
    But darnit, I would still like to know how to get my original design to work. So I should change returnBasicInfo() to toString(), you think?

  • What is the advantages of polymorphism over method overriding?

    what is the advantages of polymorphism over method overriding,that means if we are able to to create object at different instances at diff time for that sub class reff variable than what is the need of careating object of super class data type(i.e why always it is necessary to have upcasting for polymorphism?but if we can achive the same output without upcasting).....please tell me..lets have complete discuss..

    Seriously though....
    WebLogic (for which I have deployed many apps on) as
    well as Websphere are both high end Java application
    servers, meaning J2EE servers (in short). They allow
    one to deploy Enterprise Archive(EAR), a Web
    Archive(WAR), or an EJB Archive (in a JR file).
    These two servers allow one to deploy EJBs, use
    e JNDI, JMS, connectors, and other J2EE technologies
    - Tomcat does not. well, EJBs - no
    JNDI, yes - http://tomcat.apache.org/tomcat-4.1-doc/jndi-resources-howto.html
    JMS - yes (with an implementation, such as ActiveMQ: http://activemq.codehaus.org/Tomcat)
    Not sure what you mean by "connectors".
    Tomcat provides quite a bit of functionality (but yes, no EJBs)

  • What's the role of 'throws' clause in method overriding

    I'm getting error when subclass "Parser" overrides method 'getInt()' which throws Exception but super class version don't. It is compiling without error when vice versa is true i.e., super class version throws exception but sub class version don't throw exception.
    What's the role of 'Throws' clause in method overriding?
    What's the rationale with the output of following program?
    class Parser extends Utils {
       public static void main(String [] args) {
         System.out.print(new Parser().getInt("45"));
      int getInt(String arg) throws Exception{
         return Integer.parseInt(arg);
    class Utils {
       int getInt(String arg)  { return 42; }
    }

    karthikbhuvana wrote:
    I'm getting error when subclass "Parser" overrides method 'getInt()' which throws Exception but super class version don't. It is compiling without error when vice versa is true i.e., super class version throws exception but sub class version don't throw exception.
    What's the role of 'Throws' clause in method overriding?
    What's the rationale with the output of following program?
    class Parser extends Utils {
    public static void main(String [] args) {
    System.out.print(new Parser().getInt("45"));
    int getInt(String arg) throws Exception{
    return Integer.parseInt(arg);
    class Utils {
    int getInt(String arg)  { return 42; }
    Supose you do:
    Utils u = new Parser();
    int i = u.getInt("XX");This would throw a NumberFormatException, which is a checked exception, yet the compiler doesn't know this because Util.getInt() has no throws clause. Such a loophole would defeat the whole point of having throws clauses.
    So a method can only implement or override another if the throws clause on the interface or superclass admits the possibility of throwing every exception that the implementing method can throw, thus code which calls the method from a superclass or interface reference doesn't get any unexpected exceptions.

  • Need for Method Overriding

    Hi,
    What is the actual use of Method overriding? Why to override a base class method, when I can create a different method and write specific code which I would
    otherwise would have put in overriding method?
    Eg., class A{
    public void doSomething() {
    class B extends A{
    public void doSpecificThing() {     // I will not override, but create a different method
    Regards,

    855754 wrote:
    Hi,
    What is the actual use of Method overriding? Why to override a base class method, when I can create a different method and write specific code which I would
    otherwise would have put in overriding method?You know the method's name, that is, what it does. But you don't know or care how it does it.
    Here's a pretty unrealistic, but, I hope, understandable example.
    public class TaxPayer {
      public double getTaxRate() {
        return 0.15;
    public class PoorTaxPayer extends TaxPayer {
      public double getTaxRate() {
        return 0.07;
    public class RichTaxPayer extends TaxPayer {
      public double getTaxRate() {
        return 0.50;
    TaxPayer t = ... ; // get a TaxPayer somehow. Could be default, rich, or poor
    double rate = t. getTaxRate();
    // do some calculations with tax rate, income, etc. ...All we know is that t represents some TaxPayer. We don't know what kind. Different kinds of TaxPayers have different ways of calculating their respective tax rates. We don't know or care which kind of TaxPayer we have, and we don't know or care how his tax rate is calculated. All we care about is that he is-a TaxPayer, and therefore he has some way of calculating his tax rate.
    And if there's nothing special about him (not particularly rich or poor, in this example), we use a default tax rate. In cases where there's no meaningful default behavior, the method would be abstract. If all the public methods are abstract, we would create an interface to declare them.

  • 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).

  • Explain Method Overriding with respect to following program

    Hello all,
    Can anybody explain method overriding with respect to following program.
    I couldn't understand output of the program
    class Parent
    public String s = "This is Parent";
    private void method1()
    System.out.println("Parent's method1()");
    public void method2()
    System.out.println("Parent's method2()");
    method1();
    class Child extends Parent
    public String s = "This is Child";
    public void method1()
    System.out.println("Child's method1()");
    public static void main(String args[])
    Parent p = new Child();
    p.method2();
    System.out.println(p.s);          
    output:
    Parent's method2()
    Parent's method1()
    This is Parent

    In method2() of parent class, there is a call to method1().
    My doubt is how it will resolve which method to call i.e., method1() in parent or child class.
    In other words...
    if method1() in parent class is declared as public or protected then output of above program is
    parent's method2()
    child's method1()
    But if method1() in parent class is declared as private then output of above program is
    parent's method2()
    parent's method2()
    ..no matter with what object/reference variable you are calling method2()
    What is the reason behind it??

  • Overriding problems in life

    Well it's me again, having inheritance problems..
    I'm trying to override from one of the flexlib classes
    (ColoredScheduleEntry) and I notice that it's got two methods...
    override public function copy() : IScheduleEntry
    and
    override public function copyFrom(entry : IScheduleEntry) :
    void
    Now, I'm extending this class, and implementing
    IScheduleEntry but when I try to override the above functions, I
    get...
    "Method marked override must override another method" for
    both methods...which is kinda obvious, but there is a method that
    it's overriding from, and it's public too...
    Any ideas?
    Thanks

    Hi mac,
    did you mean this
    class
    ColoredScheduleEntry?
    The documentation and the code didn´t note any function
    copy or copyfrom. Are sure you that this is the right class ?
    kcell

  • Generic Method override compatibility

    I tried to find references to the problem but couldn't. I face it all the time and I thought some else must have had the same problem already.
    Oh well, here it goes.
    With both 3.1M4 and 3.1M5a the following code compiles without any problems.
    public interface MyIface {
        public <T> void foo(T p);
    public class MyClass implements MyIface{
        public <T extends Integer> void foo(T p) {
             //does something
    }However, javac 1.5 gives me:
    MyClass.java:1: MyClass is not abstract and does not override abstract method <T>foo(T) in MyIface
    public class MyClass implements MyIface{
    ^
    1 error
    I found many different variations to this problem, which I am not going to list here as I am trying to be concise. But for the eclipse compiler, <T extends Integer> is the same as <T> in terms of method signature. For the javac compiler these are different thingss.
    Does anyone know if this is a Bug in eclipse or javac, or if this is a known decision, which is taking both tools in different directions?
    Coconha

    Coco, you have to understand how generics work in the compiler to understand this. Basically, erasure means that all the fancy generics stuff you write in your source code gets 'erased' when it gets compiled... So:public interface MyIface {
        public <T> void foo(T p);
    }gets compiled and the resulting .class file, if you decompiled it, would actually look like this:public interface MyIface {
        public void foo(Object p); // NOTICE that "T" gets erased to plain old java.lang.Object
    }See? The same thing happens with MyClass:public class MyClass implements MyIface {
        public <T extends Integer> void foo(T p) {
             //does something
    }after it's compiled, actually looks like this inside the .class file:public class MyClass implements MyIface {
        public void foo(Integer p) { // NOTICE that "T extends Integer" gets erased to plain old Integer!
             //does something
    }Do you see what the problem is now? MyClass has a method called foo(Integer) and MyIface has a method called foo(Object). Obviously now, you see, foo(Integer) shouldn't override foo(Object). The Eclipse compiler should actually complain that you haven't implemented foo(Object) in MyClass. Do you follow?
    Let's look at your second example.public class Base {
      public <S> void foo(S a) {
        System.out.println("Base: " + a);
    public class Sub extends Base {
      public <S extends Integer> void foo(S a) {
        super.foo(a); // should be an error here! super.foo(Integer) doesn't exist!
        System.out.println("Sub: " + a);
    }Let's apply erasure manually and see why there is no error:public class Base {
      public void foo(Object a) {
        System.out.println("Base: " + a);
    public class Sub extends Base {
      public void foo(Integer a) {
        super.foo(a); // calls foo(Object a)! you could also write "this.foo((Object)a)"
        System.out.println("Sub: " + a);
    }Sub actually has two methods - foo(Integer a) which it defines explicitly - and foo(Object a) which it inherits from Base.

  • WLC 6 WLAN Override problem

    works function WLAN Override in controller WLC6?, we have tried it and it does not work, is a software problem?

    Professorguy,
    Does having to match profile name to SSID name result in not being able to have multiple authentication methods per SSID? That was supposed to be a feature of 4.0.206.
    Thanks,

  • Force method overriding

    Hi, my problem is the following: (basic sketch)
    class A {
         public void y() { ... x(1, 5); ... }
         protected void x(int i, int j) { ... }
    class B extends A {
         protected void x(int i, int j) { ... }
    The meaning of which is that B is supposed to change part of y()'s behavior.
    Now when in a project classes are modified all around, it may happen that someone changes the signature of A.x(), say to x(int i, int j, int k)
    This immediately causes that calling B.y() produces no different behavior than calling A.y(), which is not intended.
    So is there a way to force that B.x() must override a method in the base class? I would like to have it such that if A.x()'s signature changes and B.x()'s not, then a compile-time error occurs. (It makes sense if x() is some function with distinctive charasteristics, no overloaded forms, etc.)
    Maybe it can be reached somehow with abstract methods?
    Thanks,
    Agoston

    Something like this is what I've finally come up with:
    Please note that I wasn't allowed to change the fact that B extends A for other reasons in the real application.
    class A {
         protected interface I {
              void x(int i, int j);
         private static class AX implements I {
              public void x(int i, int j) { ... }
         private I getI() { return new AX(); }
         public void y() {
              I i = getI();
              i.x(1, 5);
    class B extends A {
         private static class BX implements I {
              public void x(int i, int j) { ... }
         private I getI() { return new BX(); }
    Requires a little additional work, but it's worth it so you don't have to check A if x()'s signature is still the same and B still does what you want, because whoever changes AX.x()'s signature, has to change I as well, and gets a compilation error if BX.x() isn't modified accordingly.

  • 2 override problems

    Hi,
    I've written my simple 'preFree' override and it works, but now I have difficulties to make it invoked when an object is deleted via web interface. Does somebody knows what the problem is?
    Second question is how to write more advanced override to store a copy of deleting document in my 'Archive' folder. I cannot find method to access the arichive folder from the server side if I know its path. Besides how to create a copy of the deleting document and put it to the folder?
    In the documentation there is S_Folder method addItem(S_PublicObject, S_LibraryObjectDefinition) but I cannot understand why it has 2 params and what the meaning of each of them is? If S_PublicObject is my copy which I want to add to the folder, what the second one is for and how to crate the copy? And if the S_LibraryObjectDefinition is a definition to create my document copy, what the first param is for?
    Has anybody managed to create archiving mechanism in iFS and can give me some clues because I'm really lost at this moment?
    Thanks in advance for any help.
    null

    mtt
    null

  • HashMap , int [][] - key , compareTo override problem , help

    i've a hashmap Map<int [][] , Integer> and i want to get the corresponding value for int a[][] from the map.
    if i use , map.containsKey(a)
    it doesn't compare as required( it doesn't consider order )
    so i thought of using class key implementing comparable like this,
    class key implements Comparable
              int a[][];
              public key(int p[][])
              {     a=p;     }
              public int compareTo(Object o)
                            key k = (key)o;
                   for(int i = 0 ; i < 3 ; i++)
                        for(int j = 0 ;j < 3 ; j++)
                             if(a[i][j]!=k.a[i][j])     return 1;
                   return 0;
    }now when i create a key ,
    key KK = new key(a) // a is int[][]
    map.containsKey(KK) doesn't invoke compareTo method itself ..
    don't what the problem is.
    but when i try . TreeMap it invokes compareTo method
    but don't know why , it acts as before when Map<int [][] , Integer> was used.. any idea
    Thanx

    manishmulani@nitk wrote:
    wil the following way of overriding hashcode work??
    class key
              int a[][];
              public key(int p[][])
              {     a=p;     }
              public boolean equals(Object o)
                   key k = (key)o;
                   for(int i = 0 ; i < 3 ; i++)
                        for(int j = 0 ; j < 3 ; j++)
                             if(a[i][j]!=k.a[i][j])     return false;
                   return true;
              public int hashCode()
                   return a.hashCode();
    NO! When doing that, you will get undesirable results. Execute the following lines of code and examine the output:
    System.out.println(new int[][]{{1,2},{3,4}}.hashCode());
    System.out.println(new int[][]{{1,2},{3,4}}.hashCode());This is better:
    public int hashCode() {
      int hash = 1, mutliplier = 1;
      for(int[] row: array) {
        for(int val: row) {
          hash ^= (val * mutliplier);
          mutliplier *= 10;
      return hash;
    }(Untested!!!)
    ok this will be same if i use TreeMap and implement Comparable<key> and override compareTo() right??Err, yes, more or less. Of course, a HashMap and TreeMap are not the same.

  • I have a basic applet method timing problem with Firefox (and Chrome), not IE nor Opera. Works if JavaScript issues windows.alert() prior, fails otherwise.

    I have an applet method, which is invoked from a JavaScript function, that is triggered by the window.onload event. The problem seems to center in the loading of the applet and its methods.
    If I step through the 3 applet acceptance prompts (I chose to use a down-level Java), the applet method is never invoked, nor is an exception raised. How this happens is beyond my understanding.
    As additional information, the Init(), start(), and "desired" Java methods all use the synchronized keyword. This is an attempt to minimize the exposure to a multi-thread environment.
    If I issue a message from JavaScript (via window.alert()) PRIOR to invoking the method, I can get the desired results in special circumstances:
    1) When the alert is presented, Firefox also prompts, SIMULTANEOUSLY, to block/continue the applet (the first of the 3 applet acceptance prompts). I can accept that these are separate threads.
    2a) If I walk through the 3 applet acceptance prompts FIRST, and then hit the OK button on the alert message SECOND, I get the desired results, my applet method executes, and all is well (other than the fact that I would prefer not to have the alert in place at all).
    2b) If I hit the OK button on the alert message FIRST, and then walk through the 3 applet acceptance prompts SECOND, I get the same results as when the page loads WITHOUT the alert, which is the applet method is never invoked, nor is an exception raised. Weird, huh?
    The above problem only occurs when the browser and the applet's URL are loaded for the first time.
    Subsequent invocations (after the page & applet has been loaded initially) do not have the failing symptoms.
    It is my understanding that IE and Firefox (and Chrome and Opera, for that matter) each use the same implementation of JavaScript provided by Microsoft. Please correct me if this information is inaccurate.
    The failing page and it's applet are proprietary; I cannot provide the Internet URL, nor the Java or JavaScript source, to aid in your analysis.

    I can speak to the source code, but have no access to it.
    The current process/thread that invokes an applet method must check to see that the applet is not currently being loaded by another process/thread. If it is being loaded, the current process/thread should block until the load is complete, THEN attempt to invoke the applet method.
    Please forward my concern to a knowledgable developer. The nature of the problem, once identified, can be addressed in a very straightforward manner.

  • HDV 1080i to Standard def DVD "Ken Stone" method- interlace problems, help!

    Greetings,
    I am on a tight deadline to produce a standard def DVD for an art exhibit, from HDV material that was imported and edited natively in FCP 7 as 1080i. I used the "Ken Stone" method of exporting the 10 minute sequence using QT conversion, as a pro res 422 HQ quicktime movie, then I took it into compressor 3.5 to make a Mpeg-2 file for a standard def DVD.
    The problem is that the video that came out of compressor, when simulated in DVD SP 3.5 (and also when burned on DVD) has weird "interlaced" looking edges whenever there is movement in the video. It is a figure against a black background, and whenever the figure moves back and forth against the black background, the edges of the figure show interlaced-looking lines. The rest of the video where there is slow movement looks fine. BTW, motion was set to "Best" in compressor.
    What am I doing wrong? was there something not mentioned in Stone's walk-thru, having to do with de-interlacing, or something I have missed? Is there a better way to produce a standard def DVD from HDV 1080i material?
    Thank you so much for your help. I am down to the wire on this one...
    AKJ

    exporting the 10 minute sequence using QT conversion, as a pro res 422 HQ quicktime movie...
    You are adding an unneeded compression cycle for a start. Export with QuickTime Conversion always recompresses your footage, even when you use the same settings as your Timeline.
    Export to QuickTime with Current Settings, Self Contained will give you a Master file that is identical to what you edited.
    weird "interlaced" looking edges whenever there is movement in the video...
    If your source material is interlaced it will look odd on a computer monitor. It will display correctly on a TV set.
    having to do with de-interlacing, or something I have missed?
    Deinterlacing will throw away half of the vertical resolution. Bye bye HD. No good can come of that, right?
    What is your intended delivery format? Does the method that you are currently using to view the material compare with how the end product will be seen?

Maybe you are looking for

  • Migration internal order group

    Hi all, I am doing the migration program for internal order group creation.(KOH1) I have used the FM for BAPI_INTERNALORDRGRP_CREATE and BAPI_INTERNALORDRGRP_ADDNODE                      for creating internal order group. using those FM in my program

  • How to config lineakd.conf to work with firefox

    I've been to the last step of setting up lineak, but I found that the firefox can't be controlled by command line arguments. So I'm here for a help... Is there anybody who knows how to config lineakd.conf, so that I can use my "back", "forward", "sto

  • Repeated Purge Cache error

    Every time I open Bridge I get an error that says: Bridge encountered a problem and is unable to read the cache. Please try purging the central cache in Cache Preferences to correct the situation. I have followed this direction several times and I st

  • I've lost my install discs... What can I do? .

    So, on my way home with my computer several stops were made, and during one of them, a bag was dropped unnoticed. Problem is it contained the install discs for the computer (specs at the bottom of my note). Can someone tell me if it will be possible

  • MSI system error

    Hello all I have a Kodak 5100 all in one printer a couple of days ago it stop working, I contacted Kodak support and they tried all kind of thing and told me that I have a MSI system error and that I must contact HP for correction. When I try to inst