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.

Similar Messages

  • 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??

  • 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?

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

  • Method Overriding-toString(),hashCode() and equals()?

    Hi,
    In some Java Classes, I saw that
    toString()
    hashCode()
    equals()
    these 3 methods of Object Class is overloaded.
    I don't understand why and in what situation we have to override these 3 methods of Object Class.
    Thanks in advance for ur Knowledge Sharing.
    Regards,
    S.Prabu

    toString() is typically overridden in subclasses so as to output something useful about a class like instance variable values instead of just a hashvalue representing the object reference as per Object.
    hashCode() and equals() are overridden typically for use within the collections framework though you need to fully understand the hashing contract before starting to override these as they can cause strange results if not overridden correctly.
    Take a look at collections and specifically the hashing functionality of HashMap and HashSet for more info on these.

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

  • JNDI + method + overriding....... Plz

    Hi Fom
    I am a new beee....... and have a method as below.... from Jboss examples...
    public static CustomerHomeRemote getInitialContext(String  jndiName)
    throws javax.naming.NamingException {
      java.util.Properties p = new java.util.Properties();
            p.put(Context.INITIAL_CONTEXT_FACTORY,"org.jnp.interfaces.NamingContextFactory");
            p.put(Context.URL_PKG_PREFIXES, jboss.naming:org.jnp.interfaces");
            p.put(Context.PROVIDER_URL, localhost +":1099");
            Context jndiContext = com.titan.jndis.JndiRefrence.getInitialContext();
            Object obj = jndiContext.lookup(jndiName);
            CustomerHomeRemote home = (CustomerHomeRemote) javax.rmi.PortableRemoteObject.narrow(obj, CustomerHomeRemote.class);
            return home;
        }I f i want to create a common method so as to overrid the function as above and pass the 'HomeRemote' to return the home object for different
    ejb's for different classes of 2 or more ejb...
    What is the type cast one should use with
    getInitialContext(String jndiName, ????)
    How to do the same Plz
    With regards
    Karthik

    I recommend you to go thru ServiceLocator pattern. You accept the JNDI name and beans home class as parameters and according to this get your bean's reference.

  • On static method override-

    just posted an example of over riding a static method . Is this legal? I mock cert exam is saying that static methods can not be overridden, What's the truth?

    As I know static method cannot override by non-static method and vice versa.

  • Forced method implementation

    Where do I go to suggest modifications to the Java language?
    I sometimes have a method that I wish to implement in a class and force all sub-classes to implement this method as well. There is not really any way in java to do this.
    A good example (although I could give many more) is the clone() method. I want a super-class to be able to implement the clone() method to copy all of it's fields. I then want a sub-class to implement the clone() methd to copy the fields specific to that sub-class. The problem is that if the sub-class doesn't implement the clone method, everything still compiles just fine, you just blow up at run-time wondering why you only have half an object.
    I first thought that you could simply revise the rules surrounding the abstract keyword so that it allows you to provide implementation in an abstract base class and still require sub-classes to implement, but this doesn't work if your base class is concrete as well.
    As this is the opposite of final, I looked up final in a Thesaurus and ended up with "elementary." Any other suggestions?
    Where do I write this up?
    thanks.

    Are you kidding me?
    I mean, I know that deep inheritance chains are clues to a bad design, but often? Take a look at the java libraries, bub! Reader and InputStream, e.g.
    Take a look at the most basic example of inheritance: shape. A line is a shape. So is a circle, but they both sub-class the draw method. A rectangle is also a shape, but it has sides unlike a line or a circle, so it has extra properties. Every math textbook I've ever seen says that a rectangle is a special case of square, and you're telling me it might not be a sub-class because it needs to store the values of it's sides separately?
    I'm not defending my design, because I don't feel like I have to. This is not an exception type of thing. There's far too many good reasons to do something like this for you to tell me this is a bad idea without me even providing an example.
    But sense I'm a fair guy, I will anyway.
    I have a Person class. Person is important in our system because it is a container of name, address, social security number, etc. Lots of information. It is a concrete class because there are people in our system who simply pass in and out without us doing anything with them.
    Extended from person are classes Administrator and Participant, which, even though they are siblings, they are as different as night and day. An administrator is a contact point, not even a user, with special business rules. A participant is the person we're interested in in our app with specialized business rules and state that evolves over the course of time, sometimes years.
    Do either of these seem like they're not people because they have lots of additional information other than what the person class does? Or maybe you think that simply because it has a concrete base class it shouldn't have a clone method?
    Because if I don't implement the clone method at the person level, both sub-classes have to know all that stuff about their super-class which breaks encapsulation.
    How about asking a question or two next time before jumping to conclusions about other people's code?

  • Static methods  overriding?

    public class SM{
    static void doit(){System.out.println("SM static method");}
    public static void main(String[] args) {
    SM s = new SM();
    s.doit();
    public class SMsub extends SM{
    static void doit(){System.out.println("SM static method this is a subclass");}
    public static void main(String[] args) {
    SMsub s = new SMsub();
    s.doit();
    }

    I think what you have done is perfectly legal, however this is more like "overloading", rather than "overriding" which is the term used in case of polymorphism. Since these methods are static there is no question of polymorphism.

  • Final method - override - content assist bug

    Hi
    I don't know if it's the wrong place to post bugs or if this bug has already been posted, but if the answer is positive just delete the topic.
    It might not even be a bug, but it looks like to me so, so I'm posting.
    I have a class which has a final (protected) method. I have a second class which extends the first class. I write:
    override protected function
    I click space, content assist pops up and I can choose the method that is marked as final.
    I guess it's a bug, because obviously there's a compile error.
    I hope it's helpful.
    Cheers,
    TR

    Known bug https://bugs.adobe.com/jira/browse/FB-25996.
    We do occassionally file bugs on behalf of users that post on the forum. To be 100% sure your bug gets filed though, log it at http://bugs.adobe.com/flex. I'm lucky in that a bunch of this is in my browser history. However, your best resource for bugs is our bug database.
    Jason San Jose
    Software Engineer, Flash Builder

Maybe you are looking for

  • How to export a video at a moderate certain format and size in premiere CC 2014: No Huge File Results!

    I have the latest version of Adobe Premiere, CC 2014 but whenever I want to render and export a video that is typically 70 megabytes in size I can't seem to always see how big the file will end up being for all the formats and I don't want to end up

  • Filmstrip Navigation - How to GoTo 1st or Last entry

    This maybe a very simple thing but I can not find it. When in Library mode I want to move around the filmstrip (at the bottom) when in Loupe View.  The same can be said about being in Grid View.  I am able to go to the next or previous slides with th

  • OOP ABAP

    Hi. Send me material on OOP ABAP if anyone have. my mail id is: [email protected] Thanks.

  • Migration assistant all or part

    I have a new MBP Retina that I'm trying to set up from an older MBA & MBP.  Is it possible to use migration assistant only selecting the files you want?  Or is it all or nothing? Trying not to completely double or triple up things as there are parts

  • Video effect help

    Speaker Knockerz - Erica Kane - YouTube anyone know how to do this effect at 54 seconds blurring with the different colours