File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes static and classes Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static and classes" Watch "static and classes" New topic

static and classes

Bill Nelsen

Joined: Aug 11, 2004
Posts: 27
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 cannot resolve symbol
symbol : method E ()
location: class D

In both instances, we are dealing only with static entities. So why do static classes need to be instantiatated??
Mike Gershman
Ranch Hand

Joined: Mar 13, 2004
Posts: 1272
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 ]

Mike Gershman
SCJP 1.4, SCWCD in process
I agree. Here's the link:
subject: static and classes
It's not a secret anymore!