Java Enum definition

后端 未结 7 647
孤独总比滥情好
孤独总比滥情好 2020-11-22 17:24

I thought I understood Java generics pretty well, but then I came across the following in java.lang.Enum:

class Enum>
         


        
7条回答
  •  一生所求
    2020-11-22 17:35

    This can be illustrated by a simple example and a technique which can be used to implement chained method calls for sub-classes. In an example below setName returns a Node so chaining won't work for the City:

    class Node {
        String name;
    
        Node setName(String name) {
            this.name = name;
            return this;
        }
    }
    
    class City extends Node {
        int square;
    
        City setSquare(int square) {
            this.square = square;
            return this;
        }
    }
    
    public static void main(String[] args) {
        City city = new City()
            .setName("LA")
            .setSquare(100);    // won't compile, setName() returns Node
    }
    

    So we could reference a sub-class in a generic declaration, so that the City now returns the correct type:

    abstract class Node>{
        String name;
    
        SELF setName(String name) {
            this.name = name;
            return self();
        }
    
        protected abstract SELF self();
    }
    
    class City extends Node {
        int square;
    
        City setSquare(int square) {
            this.square = square;
            return self();
        }
    
        @Override
        protected City self() {
            return this;
        }
    
        public static void main(String[] args) {
           City city = new City()
                .setName("LA")
                .setSquare(100);                 // ok!
        }
    }
    

提交回复
热议问题