您的位置:首页 > 编程语言 > Java开发

Java的基础知识1

2016-07-24 16:57 435 查看
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、重写方法需要抛出与原方法所抛出异常类型一致异常或不抛出异常。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: