Inheritance of static members

I realise that this is a very basic question but I'm hoping that someone will explain the answer to me. I have two classes, one extends the other and both have instance variables assigning a name to the object when it is instantiated. The superclass also has a print method which displays the name of the object. When the superclass and subclass are tested, both print their own names. However, if I make the name variables static, as well as the print function in the superclass, when I call printName on both superclass and subclass, both print the name of the superclass. Why? I had understood that static members were inherited in the same way as instance members.
public class MySuper{
     protected static String myName = "Super";
     protected static void printName(){
          System.out.println(myName);
public class MySub extends MySuper{
     protected static String myName = "Sub";
}MySuper.printName(); prints "Super"
MySub.printName(); prints "Super"

A static method uses static variables of the class
itself unless otherwise specified.So why doesn't MySub use it's own variables?
It does; the problem is that there are two variables with the same name. By default it is the variable of the class where the method is declared in, so MySub.printName() uses the variable MySuper.myName. Declaring a new variable in the subclass, static or not, does not override or replace the variable in the superclass, it simply hides it from the methods of the subclass.
When you inherit a method, it is not copied intothe SubClass, it is only available to be
used from this SubClass.
That was what I was trying to imply. That the
printName method is inherited by MySub and is
available to be used by MySub.
So MySub can use printName() (from MySuper) and
executes this on it's own variable myName="Sub".
No, it uses the superclass variable; subclass variables don't replace superclass ones.
Why
is that not happening with my static example when
that's exactly what happens with my non-static
example? Where is the difference?
There is no difference; you will see the same thing happen with instance methods:class MySuper {
    String myName = "Super";
    void printName() {
       System.out.println(myName);
class MySub {
    String myName = "Sub";
}When you call printName for an object of class MySub, you'll see "Super" printed.

Similar Messages

  • Static block in superclass to initialize static members in subclasses

    I am trying to create several classes that are all very similar and should derive from a super class because they all have common members and are all initialized the same way. I would prefer every member of my subclasses to be static and final as they will be initialized once and only once. I can not figure out the best way to make this work. Here is an example (using code that does not work, but you can see what I am trying to do):
    class Super
        protected static final String initializedInEachSubclass;
        protected static final String alsoInitializedInEachSubclass;
        // these need to be accessed from anywhere
        public static final String initializedInSuperclass;
        public static final String alsoInitializedInSuperclass;
        // this static initialization block is exactly the same for every instance
        static
            // initialize these based on what the subclasses initialized
            initializedInSuperclass = initializedInEachSubclass + alsoInitializedInEachSubclass;
        private Super () {} // never instantiated
        public static final String getMoreInfo ()
            // the same for each instance
            return Integer.toString (initializedInEachSubclass.length ());
    class Sub1 extends Super
        static
            initializedInEachSubclass = "My String for Sub1";
            alsoInitializedInEachSubclass = "My Other String for Sub1";
        private Sub1 () {} // never instantiated
    }The problem with the above code is that the static block in Super uses static final variables that have not been initialized yet. I can't make Super abstract. If I initialize the final variables in Super, then I can not reinitialize them in Sub1. But if they are not final, then they could be changed after being initialized (which I would rather not allow). I could make everything protected and not final and then make public get... () methods, but I like accessing them as attributes. It seems like this should be possible, but everything I have tried has led me to a catch-22.
    Any ideas on how I can put all my redundant initialization code in one place but still allow the subclasses to initialize the static members that make each of them unique? I will be happy to clarify my examples if you need more information.
    Edited by: sawatdee on Jan 3, 2008 9:04 AM

    sawatdee wrote:
    I am basically trying to avoid having redundant code in several classes when the code will be exactly the same in all of them.That's the wrong reason to subclass. You subclass to express type specialization. That is, a Dog IS-A Mammal, but it's a special type of Mammal that implements certain common mammal behaviors in a dog-specific way. A LinkedList IS-A List, but in implements common list operations in linked-list-specific ways.
    I don't really need to have the static final members in a superclass (and I don't even need a superclass at all), but I don't know how else to execute a big static initialization block in several classes when that code is exactly the same in all of them. Without knowing more details about what you're trying to do, this sounds like a case for composition rather than inheritance. What's now your superclass would be a separate class that all your "sublasses" have a reference to. If they each need their own values for its attributes, they'd each have their own instances, and the stuff that's static in the current superclass would be non-static in the "subs". If the values for the common attributes are class-wide across the "subs", the contained former super can be static.
    public class CommonAttrs {
      private final String attr1;
      private final int attr2;
      public CommonAttrs(String attr1, int attr2) {
        this.attr1 = attr1;
        this.attr2 = attr2;
    public class FormerSub1 {
      private static final CommonAttrs = new CommonAttrs("abc", 123);
    ... etc. ..

  • Life and memory space for static members of a class

    hi,
    as we all know that instance members reside on heap inside object to which they belong, where do the static members reside on the heap or on stack..

    All objects reside on the heap.*
    *I think Java 6 or 7 may allow purely local objects to live on the stack, but if an object is referred to by a member variable--whether static or not--it will live on the heap.                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Usage of non static members in a static class

    Can you explain the usage of nonstatic members in a static class?

    Skydev2u wrote:
    I just recently started learning Java so I probably know less than you do. But from what I've learned so far a static class is a class that you can only have one instance of, like the main method. As far as non static members in a static class I think it allows the user to modify some content of the class(variables) even though the class is static. A quick Google help should help though.Actually the idea behind a static class is that you dont have any instances of it at all, its more of a place holder for things that dont have anywhere to live.
    Non-static members in a static class wouldnt have much use

  • Static vs Non--Static members

    I'm having some trouble trying to understand the differences between static and non-static members.
    I've read a few online information about static members, but I don't understand the purpose of static members.
    Can someone try to explain the main points of static members and the differences between static and non-static members?

    I'm having some trouble trying to understand the
    differences between static and non-static members.
    I've read a few online information about static
    members, but I don't understand the purpose of static
    members.
    Can someone try to explain the main points of static
    members and the differences between static and
    non-static members?Static means only one per class. If you have a Class and generate 20 objects of this class or more, they all share the same copies of any static variables. This is as opposed to instance variables of which each Object has its own. If an object changes one of its instance variables, this doesn't affect another object's instance variables.
    Having said this, however, vague and general questions are great if you are face to face with a tutor where you can have a conversation but are very difficult to answer in this format. Your best bet is to go through several online articles (and there are many good ones, just google for them) and then coming back with specific questions. Another option is to go through a book or two. Most have a chapter covering this.
    Message was edited by:
    petes1234

  • Factory class and static members

    I don't understand very well why sometimes you can find a factory class (for example for the xml parsers). What's its aim?
    And why sometuimes, instead of a constructor, some classes have only static methods that returns a reference to that object?
    Anyone can tell me?
    Thanks

    Static memebers can be used in places where instances of its enclosing class is not neccesary.Only a method is required to be executed. Let me tell you with an example,
    class ConnectionPool {
    public static giveConnection(int index) {
    In the above example, our objective is to use only the method public static giveConnection(int index) {} , and not any of the other attributes of this class. You have 2 ways to use this method : One is, you can instantiate ConnectionPool p = new ConnectionPool(); . Second is , just use ConnectionPool.giveConnection(2);
    The first solution may create instance and obstruct your performance. Seond one does not do that. All invokers of this method do not instantiate and occupy space.
    Usually, factory classes have static members. Because these classes are used as a supporting processing factory. Theses members can be considered as utility methods. Hence static property will better suit for them. This answer will also tell you that the use of constructors here is not neccessary.
    Hope this has helped you.
    Rajesh

  • Your Opinions: Inner Classes Need static Members

    Hi All,
    I want to solicit opinions for a minor change to the way inner classes work. I submitted this as an RFE to Sun and they rejected it, really without giving a reason. I'd like to know your opinions. If there is strong support I will repost the RFE.
    As you probably know, inner classes cannot have static members. The following generates a compiler error:import java.util.*;
    public class MyClass {
       class MyInnerClass {
          // Next line causes compiler error...
          static Map m = new HashMap();
    }In order to get around this you have to make the Map variable a static member of the containing class:import java.util.*;
    public class MyClass {
       static Map m = new HashMap(); // so much for encapsulation...
       class MyInnerClass {
    }I am suggesting that inner class be allowed to contain static members. Here's my reasoning...please comment:
    There are times when members (i.e., fields and methods) rightfully belong to the class as a whole, not to any particular instance of a class. I'm sure we've all found times when it was necessary to have static members in our classes. The same issues that necessitated using static members in top-level classes make them desirable for inner classes as well.
    Designing a class as an inner class is a step toward encapsulation. By forcing static members that logically belong in an inner class to be declared in the containing class is to crack the encapsulation, IMHO.
    Even though a containing class has access to all of an inner class' members (including private members) and vice versa, I think the notion of inner static members still is more OO-ish.
    What are your opinions? Would allowing inner classes to contain static members make Java more object oriented? I think it would.
    Technically, I don't think there's any reason this cannot work since the JVM has no notion of inner classes, per se.
    What do you think?

    an inner class is effectively a non static instance
    variable of its enclosing class. Instance member, but not a variable. it's a class, a type, not a variable.
    >
    I think the problem here is that making a field static
    means more than just that that field and its value are
    common to every instance of the class. It means that
    the value is valid without an instantiation of that
    class.
    Since the class itself must be instantiated (it is
    not static), What do you mean, excatly, by "_must_ be instantiated"? You are not ever "required" to instantiate anything unless you want to use it.
    you can't have static member data inside it. I don't see how this follows from the previous part of the statement.
    How would you reference the static member data of
    the inner class? You would have to specify an
    instance of the inner class, and since this breaks
    the meaning of static, you can't have static members
    in an inner class.How about outerObj.InnerClass.staticMember The syntax is well defined. The question at hand is, do we really want to allow this? The syntax to do this should only be an issue after that question has been answered in the affirmative. The people at Sun have decided not to allow it, so for now, syntax is a non-issue.
    >
    if you wanted a static member in an inner class you
    could put it in a super class of the inner class...Or in the enclosing class, as suggested in the orginal post.

  • JVM and static members of classes

    Hello Experts,
    I have applet project. Recently I reorganized the code and I made so many class members "static".
    The applet starts from javascript link from browser. When I start it at first time, everythink is OK,
    but when I start it second time there is a problem with these static members(Actually they are dialogs,
    panels, vectors and s.o.) They are saved in the memory in some way. When I close the parent browser(the browser
    that holds the javascript link) and then start again, everything is OK, because I starting applet for
    first time.
    How can I make the following calls like the first one ?
    Please help me !
    Best Regards,
    Valeri

    When u are opening a browser the static variables
    are persistance unless u closed the window.
    so while u are opening the second time the
    static variables are not initalizing.
    so if u remove the static .
    Or after displaying the applet u initialize the
    staic variable.

  • Static members & the lifespan of a midlet's memory?

    consider a midlet with the following simplified code:
    static Image img;
    startApp()
      if (img == null)
        img = Image.createImage("foo.gif");
      else
        print("IMAGE IS ALREADY IN MEMORY, NO NEED TO RELOAD IT");
    }on sun & sony erricson midp2 emulators, the 2nd time this midlet is started: the image is already in memory, i assume because of the use of "static".
    but then, does it mean that when exiting a midlets, static members are always kept alive?
    for how long?
    which kind of memory is used? (heap i assume...)
    what about other midlets: will they suffer from much-less-of-available-heap for running?

    This does not happen on the phones, do not count on it.

  • [svn:fx-trunk] 10891: Fix for ASDoc throws error when using getter methods for pseudo-inheritance of static constants

    Revision: 10891
    Author:   [email protected]
    Date:     2009-10-06 09:46:47 -0700 (Tue, 06 Oct 2009)
    Log Message:
    Fix for ASDoc throws error when using getter methods for pseudo-inheritance of static constants
    QE notes: None.
    Doc notes: None
    Bugs: SDK-22676
    Tests run: checkintests
    Is noteworthy for integration: No
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-22676
    Modified Paths:
        flex/sdk/trunk/modules/compiler/src/java/flex2/compiler/asdoc/AsDocUtil.java

    Have you tried using com.adobe.air.crypto.EncryptionKeyGenerator instead?

  • Main accessing non static members

    How can main access non static members itself being static?

    Why would you want to?
    Main has one purpose and one purpose only, it is there for kicking off a program and ensuring it closes cleanly. I know they generally don't teach this early on in programming classes, but in my opinion they should.
    You should never ever be doing any data processing in main. In some cases you may need to set data in main, like for example if the class the main is in is part of a larger project but you want to be able to test the class stand-alone without having to run the rest of the project. But in most cases main should do nothing with any data save the args, which should usually just be passed along.
    The reason behind this is simple, soon enough you will be writing programmes that span multiple class objects, only the main of the class you use to kick it off ever gets touched, so any data processing that is in the other classes main methods, never happens.
    Why you should learn how to get out of main now is, you may want to use the class you are writting now as part of a future project. But again you have the problem of unless this class is the one that kicks that project off, any processing in main does not happen. Plus what happens if you want to process the data in you are processing in main somewhere else? Code re-use of code in main is a no go.
    Plus, by getting out of main you no longer have to worry about that whole static/ non-static issue.
    JSG
    Sorry, this is just one of my pet-peeves

  • Can't remove static members using "Manage Group Members"

    Using the OAM 10.1.4.2 Group Manager app, I can remove static members from a group by modifying the Member property, but I can't remove members using the "Manage Group Members" page.
    When I search for members using that page, I get a list of the current members with an unselected checkbox for each. If I check the box next to a member and click Save, the member is not removed from the group. I turned on trace-level logging and saw that the correct user is being passed to the Identity server to be removed, but I haven't yet found anything to indicate why the removal doesn't work.
    Has anyone else run into this issue?
    Thanks,
    Matthew

    Hi Vinod,
    I'm running on Window 2003 against a Microsoft ADAM directory. I turned on diagnostics and re-ran the test using both "Manage Group Members" and modifying the property directly-- from what I can tell, the ldap modify only happens when I modify the property.
    (I had also noticed the problem with the instructions, but I eventually figured it out-- if I can get this working, I'll have to fix the verbiage before I deploy.)
    Any ideas? What platform and directory are you using?
    Thanks,
    Matthew

  • Singleton with static members only

    If I have a singleton class with static members only and I'd like to ensure that nobody accidentally instantiates the class, would it make sense to declare the class abstract? Or instead should I leave it non-abstract but make the no-argument constructor private? Or both?
    Which of these approaches would you recommend?
    Thanks.

    pros of using classical singletons (per Head First
    Design Patterns):
    1) It ensures that one and only one object is
    instantiated for a given class.This is effectively the same as using a non-instantiable class with all static members. You don't have an instance, but you have exactly one of it.
    2) It gives a global point of access like a global
    variableAgain, same thing with a non-instantiable class with all static members.
    3) It is only created when you need it (unlike a
    global variable) and thus wastes no resources if it
    is not needed.Again, same thing.
    Also, Java does not have global variables.
    Also, no variable in Java requires more than 8 bytes, and most are 4 or 2.
    4) Using a static self-contained class in place of a
    singleton can be a source of subtle, hard-to-find
    bugs often involving order of initialization of
    static code.Eh? Example please?
    5) Global variables encourage developers to pollute
    the namespace with lots of global references to small
    objects.What global variable? Java doesn't have global variables? How is a class full of statics any more a global than a "real" singleton?

  • Packages, import and Inheriting with static

    Hello.
    I am programming a program, in which the main class (file: Main.java) uses objects declared in Components.java.
    The problem is, the import of the components only works if I explicitly make the main class inherit from the components class with whose objects being declared as 'static'. A simple import instruction, the way I learned it, in the main class such as 'import <project>.components;' does not work.
    Sample code:
    Current state; working
    Main.java:
    package <project>;
    public class Main extends Components {  
        public static void main(String[] args) {
            start();
    }Components.java:
    package <project>
    public class Components {
        public static void start() {
            // code
    }Desired:
    Main.java
    package <project>;
    import <project>.components;
    public class Main {  
        public static void main(String[] args) {
            start();
    }Components.java:
    package <project>
    public class Components {
        public void start() {
            // code
    }How to realize this idea into a working program?
    Thanks in advance!

    I apologize for not conveying my problem proberly, but you have to know I did not learn Java with reference material in the English language, therefore it might happen that some terms are not translated correctly (by me) and thus not equaling the standardised terms.
    Anyway, let me try to rephrase my problem.
    I want to use the object declared in Components.java in the main class/main methode of the file Main.java. In order to achieve this goal I used inheriting, concretely the main class inherits from the components class, as a makeshift to use Components.java's objects in the main class. However this is not the way I want to accomplish my objective with.
    To make a long story short I just want to utilise Components.java's object in Main.java's main method. The manner to achieve this does not matter, though I want to do it preferably with 'import'.
    Hope this clears things up. Thank you anyway.
    Edited by: Ikaragua on May 31, 2008 6:00 AM
    Solution found.
    package project;
    public class Main {  
        public static void main(String[] args) {
            Components.start();
    }

  • Do sub classes get their own copy of base class static members?

    Hi,
    I am sub classing a certain classwhich has a static member boolean used for status updating. I have two sub classes, each needing its own static copy of the boolean. Do they get their own copy, or must I redeclare the member in each sub class?
    AC

    You must re-declare them (hiding the superclass member) if you wish the subclass members to be "independent".
    class Coin {
        public static int FOO;
        public static int BAR;
    class Coin2 extends Coin {
        public static int BAR = 2;
        public static void main(String[] args) {
            FOO = 1;
            System.out.println("Coin FOO  = " + Coin.FOO);  // 1
            System.out.println("Coin2 FOO = " + Coin2.FOO); // 1
            System.out.println("Coin BAR  = " + Coin.BAR);  // 0
            System.out.println("Coin2 BAR = " + Coin2.BAR); // 2
    }HTH! :o)

Maybe you are looking for

  • Re-encode and send to Flash Media Server?

    Hi all, I hope this is not a basic question - I'm in a bit of a loop with this. I need to do two things: grab a live video feed from a professional DV camera - the feed would be a standard BNC (composite) video cable + XLR mic cable or similar. I nee

  • GUI_UPLOAD and OS

    hi all       i am using the function module GUI_UPLOAD in my code , i want to know as this FM takes file from presentation server and uploads  it to application server, so on presentation server is thr any relation between OS or any files from OS are

  • I want to add a photograph over an existing video.

    On the video the person intros herself as the owner of a particular establishment, and I want to fly in a photo the business for  2 seconds, while she's speaking. How do I accomplish this?

  • Optimizing and debugging code

    This question was posted in response to the following article: http://help.adobe.com/en_US/dreamweaver/cs/using/WSc78c5058ca073340dcda9110b1f693f21-7ba2a .html

  • Assignment of Business place to  Plant

    Hi, Can you please tell me where is option for assignment of Business place to Plant Regards, Yadayya