Java的基础知识1

1、对于class的权限修饰只可以用public和default,public类可以在任意地方被访问,default类只可以被同一个包内部的类访问。

2、在子类中可以根据需要对从父类中继承来的方法进行重写。
重写的方法必须和被重写的方法具有相同方法名称、参数列表和返回类型。
重写方法不能使用比被重写方法更加严格的访问权限。

3、子类的构造的过程中必须调用其父类的构造方法。
子类可以在自己的构造方法中使用super(参数列表)调用父类的构造方法,使用this(参数列表)调用本类的另外的构造方法。如果调用super,必须写在子类构造方法的第一行。如果子类的构造方法中没有显式的调用父类构造方法,则系统默认调用父类无参数的构造方法。如果子类构造方法中既没有显式的调用父类构造方法,而且父类中又没有无参的构造方法,则编译出错。

4、在进行String与其他类型数据的连接操作时,将自动调用该对象类的toString()方法。
toString()方法的解释:Returns a string representation of the object. In general, the toString method returns a string that “textually represents” this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.
【推荐所有的子类都重写该方法。】
The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@’, and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:
getClass().getName() + ‘@’ + Integer.toHexString(hashCode())
【类名+@+类的哈希编码】

5、比较两个对象是否相等可以使用Object类中的equals方法。String和Date等类重写了Object的equals方法。

public class Test{
    public static void main(String args[]){
        Dog d1 = new Dog("blue",5,6);
        Dog d2 = new Dog("yellow",5,6);
        System.out.println(d1.equals(d2));

        String s1 = new String("come on");
        String s2 = new String("come on");
        System.out.println(s1 == s2);
        System.out.println(s1.equals(s2));
    }
}

class Dog{
    String color;
    int weight;
    int height;

    public Dog(String color,int weight,int height){
        this.color = color;
        this.weight = weight;
        this.height = height;
    }

    public boolean equals(Object obj){
        if(obj == null){
            return false;
        }else if(obj instanceof Dog){
            Dog d = (Dog)obj;
            if(this.color == d.color && this.weight == d.weight && this.height == d.height){
                return true;
            }
        }
        return false;
    }
}

6、重写方法需要抛出与原方法所抛出异常类型一致异常或不抛出异常。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值