Granny's Programming Pearls
"inside of every large program is a small program struggling to get out"
JavaRanch.com/granny.jsp
Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

static and classes

 
Bill Nelsen
Greenhorn
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
In the following code:


class A {void m1() {System.out.print("A.m1");}}

class B extends A {
static void m1(String s) {System.out.println(s+",");}
}

class D {
static class E {
static void m1() { System.out.println("E"); };
}
}

class C {
public static void main (String[] args) {
B.m1("main"); // 1
new D.E().m1(); // 2
}
}

This code compiles correctly, but why does line 2 require a "new" keyword, while line 1 doesn't. Removing the "new" keyword on line 2 results in a
C.java:17: cannot resolve symbol
symbol : method E ()
location: class D
D.E().m1();

In both instances, we are dealing only with static entities. So why do static classes need to be instantiatated??
 
Mike Gershman
Ranch Hand
Posts: 1272
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
So why do static classes need to be instantiatated??

They don't, but if you are using new, you must provide a constructor ending with ().

Try this (no instantiation and no constructor):
D.E.m1(); // 2

Another point is that D.E is not really a static class, it is a regular class nested in D but not requiring a D object to be used. The "static" modifier is misleading.

D.E.m() is a true static method. When you used "new D.E()", you were instantiating and throwing away an object. You used a reference to that D.E object to access the static method m1(). This is an alternate way to call any static method.
[ January 18, 2005: Message edited by: Mike Gershman ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic