Access Modifiers Effect on Static Method Hiding Question

I am studying for my SCJP exam and have come across a question that I do not understand and have not yet found a satisfactory explanation.
Given:
package staticExtend;
public class A{
     private String runNow(){
          return "High";
     static class B extends A{
          public String runNow(){
               return "Low";
     public static void main(String args[]){
          A[] a=new B[]{new B(),new C()};
          for(A aa:a)
               System.out.print(aa.runNow()+" ");
class C extends A.B{
     public String runNow(){
          return "Out";
}The output is "High High". The explanation in the sample exam from ExamLab was that because the runNow() method in A was private that only an explicit cast to the B class would invoke the runNow() method in B. I have verified that that is the case, but am not clear on how the runNow() method being declared static in B and how the private access modifier in A results in this behaviour.
Any additional explanation would be greatly appreciated.
Thanks in advance.
-- Ryan

Ryan_Chapin wrote:
OK, so since runNow() in A is private the compiler determines that regardless of the available methods in any of it's sub classes that since we declared the original array reference as "A" that it will invoke the runNow() in A. It's also due to the fact that the invocation came from within A. You would have gotten a compile time error if you tried to place the code in the main method in another class.
>
My mistake about the second part that you mention. You are correct. runNow() in B is NOT static, but the class is static. I guess that was the red herring in this question I don't see how that is related. I actually think that the "red herring" was what I described above. The fact that the code was placed in A, and that private methods can't be overridden.
and the fact that the class itself is static has nothing to do with the behaviour that is being illustrated. Is that correct?Correct

Similar Messages

  • Question about static method hiding

    I undestand that a static method may only be hidden in a subclass not overridden. But, I don't understand why an exception type thrown by the subclass method must be a subtype of the exception type thrown by the superclass method. For example,
    public class A {
    public static void foo() throws ExceptionA { }
    public class B extends A {
    public static void foo() throws ExceptionB { }
    gives a compile-time error if ExceptionB is not a subclass of ExceptionA. This makes perfect sense in the non-static case but what does it matter here?
    Thanks,
    Tim

    I don't understand your point. In either case, static
    or non-static, ExceptionB must be the same or a
    subclass of ExceptionA. My question is why this
    matters in the static case.I think it's for binary compatibility, that is, so that you can make changes to Java source files and recompile only the changed files. If you originally did not have the static method in class B, and called B.foo() in another class, the A.foo() method would actually be called at run time. If you then change the B class and add a foo() method, it must be compatible so that the other class's method call is still valid.
    If you're unfamiliar with the concept of binary compatibility, read the chapter in the Java Language Specification. It's a critical but often overlooked aspect of the Java language.

  • Can Static Methods be overridden ?

    My question is can static methods be overridden ?
    I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
    According to that thread discussion, Java language states that static methods cannot be overridden.
    To which kajbj posted a program which did allow overriding of static methods.To quote him :
    I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
    /Kaj This is one small program code which i wrote ,which did not allow static methods to be overridden,but no error as such was displayed.
    package fundamentals;
    class SuperClass
      public static String getName()
           return "HI,CLASS...SUPER CLASS";
      public int getAge()
           return 20;
    } // END OF SUPER CLASS
    public class SubClass extends SuperClass{
    public static void main(String[] args)
              SubClass objSubClass=new SubClass();
              SuperClass objSuperClass=new SubClass();
              System.out.println(objSubClass.getName());      // SUB CLASS
              System.out.println(objSuperClass.getName());   // SUPER CLASS
              System.out.println(objSubClass.getAge());        // SUB CLASS
              System.out.println(objSuperClass.getAge());     // SUPER CLASS
                     public    static String getName()
                       return "HI,CLASS...SUB CLASS";
                     public int getAge()
                        return 40;
    } // END OF MAIN CLASSWhich gives the O/P :
    HI,CLASS...SUB CLASS
    HI,CLASS...SUPER CLASS
    40
    40So,the static method was not overridden.
    But ,why was no error message displayed ?
    Also when i modify the subclass static method,by removing the static keyword as follows :
    public  String getName()
                       return "HI,CLASS...SUB CLASS";
                     }A Error Message as :
    Exception in thread "main" java.lang.Error: Unresolved compilation problem:
         This instance method cannot override the static method from SuperClassis displayed.
    Why this message is displayed after i remove the static keyword ?
    So can we say that Java does not allow static method to be overridden but does not display a compile/run time error when this is done ?
    Is this a bug as stated by kajbj ?
    Please let me know if i am not clear.If this question has been answered somewhere else in this forum,kindly let me know.
    Thank you for your consideration.

    amtidumpti wrote:
    My question is can static methods be overridden ?
    I found this thread [Can Static Method be overridden ?|http://forums.sun.com/thread.jspa?threadID=644752&start=0&tstart=0] .Since it was too old,i have created this new thread.
    According to that thread discussion, Java language states that static methods cannot be overridden.
    To which kajbj posted a program which did allow overriding of static methods.To quote him :
    I filed a bug report on it. I don't know if it's expected behaviour or not, but I expect the compiler to complain if you add @Override to a static method (since it can't be overridden)
    /Kaj
    Sigh! Amti, are you being misleading on purpose? Kaj did not "post a program which did allow overriding of static methods." He posted a program which used the annotation @Override on a static method, like this:
    class A {
        public static void m() {}
    class B extends A {
        @Override public static void m() {}
    }He wondered why it didn't generate an error message. Well, it does now:
    A.java:6: method does not override or implement a method from a supertype
        @Override public static void m() {}
        ^
    1 error

  • Calling non-static command from within static method

    Hello,
    I have a static method that reads bytes from serial port, and I want to set a jTextField from within this method. but I get error that says it is not possible to call non static method from a static one. How can it be solved?

    ashkan.ekhtiari wrote:
    No, MTTjTextField is the name of jTextFiled class instance.You haven't declared any such variable in the class you posted, not to mention that such a variable name violates standard code conventions.
    This is and instance of that object actually. You haven't declared any such variable in the class you posted.
    the problem is something else. No, it isn't, based on the information you have provided. If you want accurate guidance, don't post misleading information about your problem.
    It can not be set from within static method.A question commonly asked on Java forums concerns an error message similar to the following:
    non-static variable cannot be referenced from a static context
    In Java, static means "something pertaining to an object class". Often, the term class is substituted for static, as in "class method" or "class variable." Non-static, on the other hand, means "something pertaining to an actual instance of an object. Similarly, the term instance is often substituted for non-static, as in "instance method" or "instance variable."
    The error comes about because static members (methods, variables, classes, etc.) don't require an instance of the object to be accessed; they belong to the class. But a non-static member belongs to an instance -- an individual object. There's no way in a static context to know which instance's variable to use or method to call. Indeed, there may not be any instances at all! Thus, the compiler happily tells you that you can't access an instance member (non-static) from a class context (static).
    Once you understand this concept, you can fix your own problem.
    ~

  • Private static method

    How do I get access to a private static method of a class?
    I can't just call it by object.privatemethod() , right?

    unless your call is made within the body of the
    class, you cannot call it, otherwise just call it via
    a static ref of the class
    ObjectName.privateMethod()
    (not)
    ObjectInstance.privateMethod()...where "ObjectName" is the name of the class.
    Or you can just call it with privateMethod(), but that tends so suggest "this.privateMethod()" so I'd go with qualifying it with the class name, to be clear.

  • Singleton without Static Methods

    Hi all,
    Is there a way to make a Singleton without using static methods?
    I dont want to create new instances. I just want that single instance of a class but can find a way to access it without a static method.
    Any ideas?

    mycoffee wrote:
    gcameo wrote:
    Hi all,
    Is there a way to make a Singleton without using static methods?
    I dont want to create new instances. I just want that single instance of a class but can find a way to access it without a static method.
    Any ideas?Another way. In the class, create a static (still static) variable instanceCount
    Write a close() method and call it whenever you are done with the class
    then if the contructor is called, add 1 to the count. in the close() substract 1 from teh count
    If the contructor is called when the count = 1 throw new Exception("I want to be alone"); LOLOuch, sounds like the worst solution so far.

  • Use of public access modifier in main method

    I want to know what is the significance of public access modifier with main (String args[]) method. Like generally we write
    public static void main(String args[])
    But if we write
    private static void main(String args[])
    OR
    protected static void main(String args[])
    then also its working properly.............
    then what is the use of public keyword..........................
    Regards
    Ajay Pratap Singh

    then what is the use of public keyword..........................Convention, I believe. And I think newer versions of the JVM require it.
    P.S. Relax a bit on the punctuation overuse. Many folks around here find that a bit irritating, and you probably don't intend to send that kind of a message. Cheers!

  • I am not able access static methods from startup class

    I have a simple java class which queries the Database and holds some data. I am trying to access a static method of this class from the StartupClass and I am not able to do so. But I am able to access a static variable of the same class.
    Can someone help me here.

    Well, welcome to the world of "hacked" phones. If your purchase was from the US, you obviously purchased an iPhone that is locked to a US carrier. The iPhone must have been jailbroken and unlocked via software to accommodate your foreign SIM card. Now that you have updated the phone, it is locked back to the US carrier. Only the carrier can authorize Apple to unlock the iPhone and none of the US carriers will unlock the iPhones. Best suggestion is to sell the phone and obtain a factory unlocked version directly from the Apple store.
    To answer your other question, there is not a supported method to downgrade iOS.

  • Namespace, static method questions

    The really useful script here is
    Sephiroth's
    Actionscript 3 PHP Unserializer. I have used the old AS2
    version many times and it's totally rad. With it you can create
    really complex data objects in php,
    serialize() them, and then
    unserialize them with this code in Flash. It dramatically reduces
    the amount of code you have to write to share complex data between
    PHP and Flash.
    The problem I'm having is that the new Actionscript 3 version
    was apparently written for Flex. When I try to use it in flash, I
    get an error:
    1004: Namespace was not found or is not a compile-time
    constant.. This error refers to this line of code:
    use namespace mx_internal;
    I know next to nothing about namespaces in Flash, but best I
    can tell, that namespace constant is apparently to be found in
    mx.core.
    At any rate, if I remove all references to mx_internal
    namespace and mx.core, I can get the script working. This brings me
    to my first questions:
    QUESTION 1: What does the use of that namespace stuff
    accomplish?
    QUESTION 2: Am I likely to suffer any unpredictable consequences
    by removing that namespace stuff?
    Also, I get an error (1061: Call to a possibly undefined
    method serialize through a reference with static type
    org.sepy.io:Serializer.) when I try to call the static methods of
    the Serialize class by instantiating it and calling the methods via
    the instance like this:
    var oSerializer:Serializer = new Serializer();
    var str = oSerializer.serialize(obj);
    That's my third question:
    QUESTION 3: Is it impossible to call a static method of a class
    from an instance of the class? Do we have to reference the class
    name instead?
    Any help would be much appreciated

    nikkj wrote:
    static methods are really class messages, that is, methods that act upon an entire classification of objects not just one instance. it is an elegant means by which to send messages to all instances or rather the class itself
    Static method calls are determined at compile time,not at run time, so it is not possible for the invocation to be polymorphic.(i.e can't be overridden)
    Because the language is defined that way - via the JLS.
    There is no technological reason that precludes a language from doing it. Smalltalk does exactly that.

  • Static method,new thread performance question

    Hey guys i just have two questions about two methods used in many controllers/servlets in my app:
    1-what is the difference between calling a static method in a util class or a non static method (like methods dealing with dates i.e getting current time,converting between timezones), which is better ? 2-what is the difference between calling a method(contain too many logic like sending emails) in the controller directly or running this method in a different thread ?

    cs.student wrote:
    Hey guys i just have two questions about two methods used in many controllers/servlets in my app:
    1-what is the difference between calling a static method in a util class or a non static method (like methods dealing with dates i.e getting current time,converting between timezones), which is better ?Depends on the design. It's impossible to say straight why one way would be better than another. Programming isn't that straight forward.
    2-what is the difference between calling a method(contain too many logic like sending emails) in the controller directly or running this method in a different thread ?Threads can be run at the same time. So what you're asking is "what's the difference between doing one thing after another and doing two things at the same time".

  • Static methods in data access classes

    Are we getting any advantage by keeping functions of DAOs (to be accessed by Session Beans) static ?

    I prefer to have a class of static methods that
    require a Connection to do their work. Usually, there
    is a SessionBean that 'wraps' this DAO. The method
    signatures for the SSB are the same, minus the need
    for a Connection, which the SSB gets before delegating
    to the Static Class.Uggh, passing around a connection. I've had to refactor a bunch of code that used this pattern. We had classes in our system that took a class in their constructor simply because one of their methods created an object that needed the connection. Bad news--maintenance nightmare--highly inflexible.
    What we've done is create ConnectionFactory singletons that are used throughtout the application in order to get connections to the database. All connection factory implementations implement the same interface so they can be plugged in from other components at runtime.
    In my opinion, classes that use connections should manage them themselves to ensure proper cleanup and consistent state. By using a factory implementation, we simply provide the DAO classes the means by which they can retrieve connections to the database and even the name of the database that needs to be used that is pluggable. The DAO classes do their own connection management.
    For similar reasons, I eschew the static method concept. By using class methods, you make it difficult to plug in a new implementation at runtime. I much prefer the singleton pattern with an instance that implements a common interface instead of a class full of static methods.
    I recently needed to dynamically plug in new connection factory implementation so that we could use JNDI and DataSources within the context of the application server (pooled connections) but use direct connections via the Driver manager for unit testing (so the application server didn't need to be running). Because of the way this was coded, I simply changed the original factory to be an abstract factory and changed the getInstance() method to return a different implementation based on the environment (unit test vs live). This was painless and didn't require changing a single line of client code.
    If I had to do this using the previous code that I refactored, I would have had to change about 200 jsp pages and dozens of classes that were making calls to the static method of the previous factory or hacked in something ugly and hard to maintain.
    YMMV

  • Dynamic programming accessing static method on classes

    Hi
    I need access to a static method on a class.
    The class name is first decided at runtime.
    How do I do that?
    Regards,
    Morten

    Hello Morten
    Here is a sample program for you:
    *& Report  ZUS_SDN_DYNAMIC_METHOD_CALL
    REPORT  zus_sdn_dynamic_method_call.
    DATA: go_msglist    TYPE REF TO if_reca_message_list.
    DATA: gd_method     TYPE tmdir-methodname,
          gd_class      TYPE seoclsname.
    START-OF-SELECTION.
      IF ( 1 = 2 ).
        CALL METHOD cf_reca_message_list=>create
    *      EXPORTING
    *        id_object    = 'RECA'
    *        id_subobject = 'MISC'
    *        id_extnumber =
          RECEIVING
            ro_instance  = go_msglist.
        go_msglist = cf_reca_message_list=>create( ).
      ENDIF.
      gd_class  = 'CF_RECA_MESSAGE_LIST'.
      gd_method = 'CREATE'.
      CALL METHOD (gd_class)=>(gd_method)
        RECEIVING
          ro_instance = go_msglist.
      IF ( go_msglist IS BOUND ).
        WRITE: / 'Class is bound'.
      ELSE.
        WRITE: / 'Class is NOT bound'.
      ENDIF.
    END-OF-SELECTION.
    Obviously, that is only half of the task. You need to make the method signature dynamically as well.
    Regards
      Uwe

  • Static methods and how to access

    Hi,
    This seems like a silly quesion but i am trying to access a static method but it tells me that i cant.
    The method i am calling from is not static
    Thanks

    syntax: class name dot static method name (assuming the method is accessible): StaticMethodClassName.aStaticMethod();
    can't reference a class member (variable, object, method, ...) from a static method because a static method is not a class member (it is simply a method whose scope is confined to that of the class in which it is defined).
    example:
    class Foo
    int i;
    public static void hasSyntaxErr() // this method is not a member of Foo
    i = 0; // not allowed because i is a member of Foo
    class Fooo
    void testStatic() { Foo.hasSyntaxErr(); }
    }

  • When a static method is accessed concurrently

    When a static method is accessed by many objects symultaneously(concurrently),
    What is happened in the static method.
    Are the stacks for that method maded seperately and
    each stack doesn't influence other stacks?
    thank you in advance.

    The static objects or methods concept is clear, one
    instance for all objects.No. One instance for the class.
    , and every
    one know that, static methods is slower than
    nonstatic, Since when? I've certainly never heard that before... Do you have a reference I can look at?
    and this is as i thought because static
    methods are syncronized by default.Absoloutely not!
    All synchronization locks on an object. When you synchronize an instance method, it locks on the implicit "this"; When you synchronize a static method, it locks on the class's associated Class object.
    So two synchronized static methods in the same class can not be called at the same time, but synchronized instance methods that access static variables can all access those variables at the same time and potentially cause threading problems. In this situation you can declare the static fields volatile or wrap synchronized blocks around all code that accesses them, and synchronize on the same object (perhaps the Class object associated with the current class would be appropriate, but that reallt depends on the rest of your design).

  • Access to Class information from a static method

    There does not appear to be anyway to access the Class object from instead a static method.
    e.g. How could I convert the following code so that it works ?
    class test {
    static void printClassName() {
    System.out.println( getClass().getName() );

    The idea was to have a static method that could be
    used to make a lookup based on the classname. Being
    able to access the class name would mean that I would
    not have to reimplement for every subclass !!!!!Hmm.. what are you trying to look up? Some kind of class-specific constant information maybe?
    In general your best bet is to define an abstract method in your parent class for return of the constant value, then define a specific method in each sub-class that overrides it, retrurning the appropriate value.
    Then you're common processing just gets the value with that method.
    Using some kind of lookup on the basis of class name is much clumsier, and more inclined to run time errors. Better to use the built in virtual methods table.
    Another approach is to have the value as a parameter of the constructor of the parent class and use "super(value)" in the child classes to store
    it.

Maybe you are looking for

  • Connecting my Macbook Pro!

    Hello everyone! So, I am going to be purchasing a new television once I graduate this may for my apartment...an HDTV .. they are getting cheaper by the minute! Anyway, I have movies on iTunes and such that I want to be able to watch easily and other

  • Opening Excel file in Numbers

    I placed an Excel file in Numbers iTunes file area and synchronized, but no files are found when I open Numbers on the iPad. Please advise. jmf

  • Need an example program for function module

    Hi , I am new to ABAP. Can you please give a simple example program to extract the data from a table using Function module. Thanks for your help in advace. Regards, Vishnu

  • Nokia 5800 - does it have home screen active stand...

    Hi everyone am thinking about getting a 5800 - does it have an active standby homescreen where you can customise shortcuts and also display calendar events - as the N96 etc does ? thanks in advance

  • Photoshop CS activation

    My XP pc with Photoshop CS died.  I moved old C drive to another Dell as the 2nd drive.  I loaded CS on the new C drive but I cannot activate it.  The CS is an upgrade from PS6 which was originally on the old pc but when CS was loaded on the old pc,