Maynia's Profile User Rating: -----

Reputation: 10 Tradesman
Group:
Members
Active Posts:
48 (0.02 per day)
Joined:
17-March 09
Profile Views:
1,047
Last Active:
User is offline Nov 22 2014 04:18 AM
Currently:
Offline

Previous Fields

Dream Kudos:
0

Latest Visitors

Icon   Maynia has not set their status

Posts I've Made

  1. In Topic: question regarding static fields and inheritance

    Posted 17 Apr 2014

    This is one of those things that's not particularly intuitive, I'll give it that.

    Broadly, you can treat static fields as not inherited - the definition of a static field requires that there be only one for the entire type, and all classes that inherit from type A are ultimately of type A. HOWEVER - say you have a class A with static int variable x and an inheriting class B, the JVM/compiler will let you get away with doing this:
    B b = new B();
    int test = b.x;
    

    which looks for all the world like an instance variable. It isn't - the call to
    b.x;
    
    is treated in exactly the same way as the static call
    A.x;
    

    Good IDEs will give you a warning about this - something along the lines of 'static fields should be accessed in a static way' but it is only a warning, not an error. There are ways to finagle static variables into behaving similarly to instance variables, but it generally isn't a good idea to try it.

    One more interesting oddity of this - it allows you to look like you're referencing null!
    B b = null;
    int test = b.x;
    

    Again, that will compile and run, fetching the value of the static field x from the type A - but it's downright ugly.

My Information

Member Title:
New D.I.C Head
Age:
Age Unknown
Birthday:
Birthday Unknown
Gender:

Contact Information

E-mail:
Private

Friends

Maynia hasn't added any friends yet.

Comments

Maynia has no profile comments yet. Why not say hello?