简体   繁体   English

在Java中扩展静态类是什么意思?

[英]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: 看一下web中的一些java示例代码,我遇到了以下语法:

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. 来自C#背景,其中静态类不能从另一个类继承,我对Map类之后的extends关键字有点困惑。 What does it mean to extend a static class, and what advantages does it provide? 扩展静态类是什么意思,它提供了什么优势?

The static modifier, when applied to classes, means two very different things in c# and java. 静态修饰符在应用于类时,意味着c#和java中有两个非常不同的东西。 In c#, the static modifier on a class enforces making all of that class's members static . 在c#中,类上的static修饰符强制使该类的所有成员都是静态的 Thus, in c#: 因此,在c#中:

  • extending static classes makes no sense, so it is disallowed 扩展静态类是没有意义的,所以它是不允许的
  • the static modifier can be used on any class, not just nested classes. static修饰符可用于任何类,而不仅仅是嵌套类。

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. 但是,在java中,应用于类的静态修饰符意味着该类是嵌套它的类的静态成员 ,而不是它的成员必须是静态的。 Thus, in java: 因此,在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). static修饰符只能用于嵌套类,因为它只能用于类成员(并且只有嵌套类可以是类成员)。

There's no such thing as static classes in Java (not in the same way as in C#). 在Java中没有静态类(不像在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 . 嵌套类的Java文档中获取的代码。

In this context, static means that the Map class don't need an instance of WordCount to be instanciated. 在此上下文中,static表示Map类不需要实例化WordCount实例。

It has nothing to do with being inheritable (final is the keyword that does that, though) 它与可继承无关(尽管是最终的关键字)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM