• 类的继承和接口


    一:关于构造函数的继承

    class Grandparent {
    
        public Grandparent() {
            System.out.println("GrandParent Created.");
        }
    
        public Grandparent(String string) {
            System.out.println("GrandParent Created.String:" + string);
        }
    }
    
    class Parent extends Grandparent {
    
        public Parent() {
            super("Hello.Grandparent.");
            System.out.println("Parent Created");
           //super("Hello.Grandparent.");
        }
    }
    
    class Child extends Parent {
    
        public Child() {
            System.out.println("Child Created");
        }
    }
    
    public class TestInherits {
    
        public static void main(String args[]) {
            Child c = new Child();
           
        }
    }

     

     

         从上面的例子可以看出子类在调用构造函数时,会先调用父类的构造函数,在调用父类的函数时,如果父类的构造函数有参数,如果要调用父类的有参数的构造函数,必须加上super(参数),而且必须将super语句放在第一句。

    二:不可变类

    public final class Address
    {
        private final String detail;
        private final String postCode;
    
        //在构造方法里初始化两个实例属性
        public Address()
        {
            this.detail = "";
            this.postCode = "";
    
        }
        public Address(String detail , String postCode)
        {
            this.detail = detail;
            this.postCode = postCode;
        }
        //仅为两个实例属性提供getter方法
        public String getDetail()
        {
             return this.detail;
        }
    
        public String getPostCode()
        {
             return this.postCode;
        }
        //重写equals方法,判断两个对象是否相等。
        public boolean equals(Object obj)
        {
            if (obj instanceof Address)
            {
                Address ad = (Address)obj;
                if (this.getDetail().equals(ad.getDetail()) && this.getPostCode().equals(ad.getPostCode()))
                {
                    return true;
                }
            }
            return false;
        }
        public int hashCode()
        {
            return detail.hashCode() + postCode.hashCode();
        }
    }

    不可变的类即为不能继承的类,此类用于方便和安全的进行多线程的操作。

  • 相关阅读:
    java Future 模式
    多线程的优点和代价
    转:Java同步synchronized使用
    管程
    【移动开发人员沙龙 北京站】第二期 报名火热来袭
    POJ 3111 K Best(最大化平均值)
    坐标和依赖
    分析cocos2d-x在Android上的编译过程(1):cocco2d-x是怎样生成的Android的文件夹结构
    执行startx后Ubuntupassword正确进不去的问题
    leetcode 刷题之路 64 Construct Binary Tree from Inorder and Postorder Traversal
  • 原文地址:https://www.cnblogs.com/zll20153246/p/6055673.html
Copyright © 2020-2023  润新知