第一章 方法的重写
在子类继承父类之后,对父类方法的复写拓展。
前提: 继承关系,方法和父类重名(参数列表一样 返回值一样)。
class Person {
String name;
public int info(int num) {
System.out.println("姓名:"+name+",年龄:"+age);
return 1;
}
}
@Override
class Student extends Person{
int id;
public int info(int num) {
System.out.println("姓名:"+name+"年龄:"+age+"学号:"+id);
return 1;
}
}
//在方面名称上面添加 @Override 可以判断方法是否重写 不报错就是重写
//重写的原因是 调用方法会先到此方法查找 没有匹配才会去父类匹配
第二章 Object
Object是JDK提供的一个根基,是所有类的直接或间接父类。
常见用法
获取到一个对象对应的Class对象(反射章节)
public final native Class<?> getClass();
计算当前对象的hash值(一个对象的唯一值) 【集合】
public native int hashCode();
克隆方法,创建对象的一种方式。【克隆模式】
protected native Object clone() throws CloneNotSupportedException;
唤醒、唤醒所有、等待。线程通信。【多线程】
public final native void notify();
public final native void notifyAll();
public final native void wait(long timeout) throws InterruptedException;
public final void wait(long timeout, int nanos) throws InterruptedException;
public final void wait() throws InterruptedException;
GC(垃圾回收器)在回收堆内存时,自动调用的方法。【GC】
protected void finalize() throws Throwable { }
重要方法
toString(): 打印对象内容
public String toString() {
return getClass().getName() + "@" + Integer.toHexString(hashCode());
}
public class TestObject {
public static void main(String[] args) {
TestObject to = new TestObject();
String str = to.toString();
// 输出调用toString之后的返回结果
System.out.println(str);
// 输出了对象to
System.out.println(to);
}
}
//------输出的结果-----------
//com.mage.oop.object.TestObject@15db9742
//com.mage.oop.object.TestObject@15db9742
直接打印对象,默认调用当前对象的toString方法如果没有就去Object找。
Object中的toString打印的内容可以看做是:包名.类名@地址值。
如果需要查看对象内存在的信息就需要自己重写toString。
public String toString() {
return "type:"+this.type+" price:"+this.price;
}
equals(): 比较对象是否相等
public boolean equals(Object obj) {
return (this == obj);
}
public class Computer {
String type;
double price;
}
public class TestComputer4Equals {
public static void main(String[] args) {
Computer c1 = new Computer();
Computer c2 = new Computer();
System.out.println(c1);
System.out.println(c2);
boolean flag = c2.equals(c1);// (this == obj);
System.out.println(flag);
}
}
//类中如果没有重新定义equals方法 那么使用的是Object中的equals,比较的是对象的地址
//如果需要比较对象内容 也需要在方法内重写equals
@Override
public boolean equals(Object obj) {
if(obj instanceof Computer){ //instanceof 是用来比较对象是否属于某个类型的 如果属于则返回true 如果不属于返回false
Computer other = (Computer)obj;
return this.type.equals(other.type)&&this.price==other.price
}
else
return false;
}
其他测试:
Computer c3 = new Computer();
System.out.println(c1.equals(c3));
Computer c4 = null;
System.out.println(c1.equals(c4));
//equals 方法在使用时一定要注意调用者一定要保证不是null值,否则出现空指针异常。
//null可以给任意的引用类型赋值,但是null都不属于任意的引用类型。null通过instanceof判定从属时一定为false。
第三章 类型的转换
引用类型中的类型转换和基本数据类型的类型转换一模一样
自动转换:
大类型 变量名 = 小类型值
父类形 变量名 = 子类型对象
class F{
}
class S extends F{
}
S s = new S();
System.out.println(s);
F f = s;
System.out.println(f);
强制转换:
小类型 变量名 = (小类型)大类型的值
子类型 变量名 = (子类型)父类变量
S s1 = (S)f;
System.out.println(s1);
F f1 = new F();
S s2 = (S)f1;
//引用类型的强转一定要格外小心,基本上最好不要使用。你确定当前变量实际的类型是什么的时候,才能强转。