java - Object being static -
java - Object being static -
i seen bit of code, though think got concept of static in java bit confused. can 1 explain me, how object beingness static works?
my code:
package com.oracle.certification.sampletest; public class person { static class mail service { static string desc="male"; } static gender mail=new gender(); }
package com.oracle.certification.sampletest; public class gender { string desc="gender"; }
package com.oracle.certification.sampletest; public class human { public static void main(string str[]) { system.out.println(person.mail.desc); } }
when class human run, o/p 'gender' not 'male', though des= gender nonstatic , des=male static static inner class. don't need import classes in hman? sorry have little knowledge inner classes, first of all.
can 1 explain me, how object beingness static works?
essentially, static
in context means entity in question attached class itself, not object of class. hence, static
there 1 instance of declare:
class t { public static int staticmember = 0; // 1 variable stored in memory public int nonstaticmember = 0; // many variables stored in memory objects created class }
see what 'static' keyword in class?
however, question not misunderstanding of static classes, corner case of name resolution: declaring both type , fellow member variable same name (mail
) in 1 scope (within person
class) - while 1 might think should not possible, java language allow , defines couple of rules determine 1 use.
from jls:
a simple name may occur in contexts may potentially interpreted name of variable, type, or package. in these situations, rules of §6.5 specify a variable chosen in preference type.
... static class mail service { // type } static gender mail service ... // variable same name // - compiler chooses utilize 1 ...
hence, when referencing person.mail
, compiler chooses variable, not type (the inner class).
java static inner-classes
Comments
Post a Comment