Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does it mean to extend a static class in Java?

Looking at some java example codes in the web I came across the following syntax:

public class WordCount {

 public static class Map extends Mapper<LongWritable, Text, Text, IntWritable> {
    private final static IntWritable one = new IntWritable(1);
    private Text word = new Text();

    public void map(LongWritable key, Text value, Context context) throws IOException, InterruptedException {
        //...
    }
 }

 //...
}

Coming from C# background, where static classes cannot inherit from another class, I was a little confused about the extends keyword after the Map class. What does it mean to extend a static class, and what advantages does it provide?

like image 760
Yeonho Avatar asked May 28 '13 15:05

Yeonho


3 Answers

The static modifier, when applied to classes, means two very different things in c# and java. In c#, the static modifier on a class enforces making all of that class's members static. Thus, in c#:

  • extending static classes makes no sense, so it is disallowed
  • the static modifier can be used on any class, not just nested classes.

However, in java, the static modifier applied to a class means that the class is a static member of the class in which it is nested, and not that its members have to be static. Thus, in java:

  • extending static classes is allowed, since its members are not necessarily static
  • the static modifier can only be used on nested classes because it can only be used on class members (and only nested classes can be class members).
like image 85
James Dunn Avatar answered Sep 27 '22 17:09

James Dunn


There's no such thing as static classes in Java (not in the same way as in C#). This here is a inner nested class and the static attribute means it can be used without having an instance of the outer class.

Examples

A static nested class could be instantiated like this:

OuterClass.StaticNestedClass nestedObject = new OuterClass.StaticNestedClass();

However, a non-static inner class need to be created in relation to an instance of the outer one:

OuterClass.InnerClass innerObject = outerObject.new InnerClass();

Code taken from Java documentation on nested classes.

like image 23
Cedric Reichenbach Avatar answered Sep 27 '22 19:09

Cedric Reichenbach


In this context, static means that the Map class don't need an instance of WordCount to be instanciated.

It has nothing to do with being inheritable (final is the keyword that does that, though)

like image 39
njzk2 Avatar answered Sep 27 '22 17:09

njzk2