类的继承(学习笔记)
继承 关键字extends 实现类的继承
Java 只支持单继承
实现多态的前提
Java中所有的类 直接或者间接继承Object类
子类不继承父类的情况:
- private 均不继承
- 不继承构造方法
- 子类父类不在同一个包,使用默认访问权限的成员与方法
父类
class people{
private String gender;//子类无法继承
public String name;
public people(){}
public people(String name,String gender){
this.name=name;
this.gender=gender;
}
public void eat(){
System.out.println("父类的普通方法");
}
public void eat(String things){
System.out.print("this.普通方法");
this.eat();
System.out.println("重载普通方法");
}
}
子类
class man extends people{
public setname(String name){
this.nmae =name;
]
@override
public void eat(){
super.eat();
System.out.println("子类重写父类的普通方法");
}
}
object
public class Object {
public Object() {
}
private static native void registerNatives();
public final native Class<?> getClass();//返回一个对象的运行时类
public native int hashCode();//返回对象hashcode(可以理解为物理地址,但是不是物理地址,经过特有算法的物理地址hash映射)
public boolean equals(Object var1) {//对比两个对象是否相同,非重写等价于==
return this == var1;
}
protected native Object clone() throws CloneNotSupportedException;//克隆一个新对象
public String toString() { //对象sout输出时 默认调用的方法,返回当前对象本身的有关信息,按字符串对象返回
return this.getClass().getName() + "@" + Integer.toHexString(this.hashCode());
}
public final native void notify();//唤醒对象监视器上的等待的单个进程
public final native void notifyAll();//唤醒对象监视器上的等待的所有进程
public final native void wait(long var1) throws InterruptedException;//使当前的线程等待
public final void wait(long var1, int var3) throws InterruptedException {//使当前的线程等待
if (var1 < 0L) {
throw new IllegalArgumentException("timeout value is negative");
} else if (var3 >= 0 && var3 <= 999999) {
if (var3 > 0) {
++var1;
}
this.wait(var1);
} else {
throw new IllegalArgumentException("nanosecond timeout value out of range");
}
}
public final void wait() throws InterruptedException {//使当前的线程等待
this.wait(0L);
}
protected void finalize() throws Throwable {
}
static {
registerNatives();
}
}
继承的使用方法
- 将公共变量或者方法提取到超类
- 除非所有的方法都有继承意义,否则不要使用继承
- 在方法覆盖时不要更改原有方法的使用预期行为
this && super
调用属性
this.属性//访问当前对象的属性
this.nmae
super.属性//调用父类的属性
super.name
调用方法
this.方法();//访问当前对象的方法
this.eat();
super.方法();//访问父类的方法
super.eat();
调用构造方法
this(参数1,参数2,...);//访问当前类的构造方法
this("Tom","man");
super(参数1,参数2,...)//访问父类的对应构造
this("Tom","man");
重载
在同一个类中,对方法的重载
重载规则
- 方法名相同
- 参数列表不同(个数,数据类型,顺序)
- 与修饰符和返回值无关
重写
子类对父类,对同一个名字的方法的重写