[编写高质量代码:改善java程序的151个建议]建议38-41

38.使用静态内部类提高封装性

 
1.封装性
2.限制性。静态内部类不持有外部类的引用。对静态内部类的访问做了限制。
3.生命周期,不依赖于外部类。
 
39.
使用匿名类的构造函数
eg:
List    l1 = new ArrayList();
List l2 = new ArrayList(){};//匿名类
List l3 = new ArrayList(){ {} {} {} {} }//匿名类,构造代码块
 
40.匿名类的构造
只能以构造代码块的形式出现,不能直接有构造函数。
 
41.内部类实现多重继承
eg:
interface Father{
    public int strong();
}

class FatherImpl implements Father{
    public int strong(){
        return 8;
    }
}

interface Mother{
    public int kind();
}

class MotherImpl implements Mother{
    public int kind(){
        return 8;
    }
}
class Son extends FatherImpl implements Mother{
    @Override
    public int strong(){
        return super.strong() + 1;
    }


    public int kind(){
        return new MotherSpecial().kind();
    }//实际上可以直接 return super.kind() - 1
    
    public class MotherSpecial extends MotherImpl{
        public int kind(){
            return super.kind() - 1;
        }
    }
    
}


class Daughter extends MotherImpl implements Father{
    @Override
    public int strong(){
        return new FatherImpl(){
            @Override
            public int strong(){
                return super.strong() - 2;
            }
        }.strong();
    }
}
 
 
 
 
原文地址:https://www.cnblogs.com/akingseu/p/3485777.html