zoukankan      html  css  js  c++  java
  • 类的继承和接口

    一:关于构造函数的继承

    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();
        }
    }

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

  • 相关阅读:
    不同版本strtotime("2016-09-04")输出不同问题
    Jquery,YUI这个著名js库名称作用的理解
    函数和方法
    js的关联数组
    windows信息
    改centos7的网卡名
    GIT命令
    安装时遇到:正在尝试其它镜像。 http://mirrors.btte.net/centos/7.2.1511/extras/x86_64/repodata/repomd.xml: [Errno 14] curl#6
    本地怎样访问虚拟机上的服务器
    yolo
  • 原文地址:https://www.cnblogs.com/zll20153246/p/6055673.html
Copyright © 2011-2022 走看看