Java的基础知识1

来源:互联网 发布:1688一键传淘宝教程 编辑:程序博客网 时间:2024/06/01 16:29

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