Meaningless Drivel is fun!*
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


Win a copy of Android Security Essentials Live Lessons this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "static and classes" Watch "static and classes" New topic
Author

static and classes

Bill Nelsen
Greenhorn

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
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

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: http://aspose.com/file-tools
 
subject: static and classes
 
Similar Threads
Confusion about wrapper classes.
why this gives StackOverflowError
Dan exam doubt 19
garbage collection
Jq + Question ID :988380923984