码迷,mamicode.com
首页 > 其他好文 > 详细

类的继承和接口

时间:2016-11-11 23:07:09      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:重写   create   分享   tde   pos   return   static   main   不能   

一:关于构造函数的继承

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

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

 

类的继承和接口

标签:重写   create   分享   tde   pos   return   static   main   不能   

原文地址:http://www.cnblogs.com/zll20153246/p/6055673.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!