Static method calls to derived types over virtual implementations? (Android)

I have class A, with methods foo and bar, that are implemented by A1 and A2. The functionality in both A1 and A2 is the same. In other words:

   public class A {
       public int foo() { return 0; };
       public int bar() { return 1; };
   }

    class A1 extends A {      
        public int AnotherFooFunction() { return foo(); }
        public int AnotherBarFunction() { return bar(); }
    }

    class A2 extends A { 
        public int AnotherFooFunction() { return foo(); }
        public int AnotherBarFunction() { return bar(); }
    }

Is it better to keep the code in this fashion, or to swap out those virtual methods as static methods? (In Java, everything non-final/non-private is considered virtual, right?)

According to the Designing for Performance section in the Android Developer Docs, I should swap out these virtual methods for static ones. So the above becomes:

   public class A {
        public int foo() { return 0; };
        public int bar() { return 1; };
   }

    class A1 extends A {      
        public int AnotherFooFunction() { return A.foo(); }
        public int AnotherBarFunction() { return A.bar(); }
    }

    class A2 extends A { 
        public int AnotherFooFunction() { return A.foo(); }
        public int AnotherBarFunction() { return A.bar(); }
    }

Is this how it "ought" to be? I fully realize that I may be misinterpreting this paragraph in the docs.

Answers


There is no point in making wrappers for methods in base class, because they will be present in the derived class anyway.

Regarding to the performance tip from Android's website - what they meant is to make a method static, if you find out that it's body doesn't refer to any non-static field or method. This will remove the overhead to passing a this pointer internally.

Anyway, to bother tuning down your application for performance at such fine-grained level, you must have a proof (by profiling) that exactly this method is causing a slow down. Optimizing random portions of the code, even if it's based on a guess, is a waste of time.


This is the best option for you

   public abstract class A {
       public int foo() { return 0; };
       public int bar() { return 1; };
   }

    class A1 extends A {      

    }

    class A2 extends A { 

    }

A1 and A2 inherit the foo() and bar() methods automatically.

Don't worry about optimization right now, focus on good OO programming, if it is slow come back and optimize the problem areas when you are done.


Need Your Help

PHP MySQL query fail error

php mysql sql database

I am trying to sum from a query but I get error, here is the code