super详解
package com.oop.Demo05;
//学生is人 派生类 子类
//子类继承了父类,就会拥有父类的全部方法!
public class Student extends Person{
//ctrl+H 显示继承关系
private String name = "siri";
public Student() {
//隐藏代码:调用了父类的无参构造
super();//默认调用了父类的无参构造器,必须要在子类构造器的第一行
System.out.println("Student的无参构造");
}
public void print(){
System.out.println("Student");
}
public void test1(){
print();
this.print();
super.print();
}
public void test(String name){
System.out.println(name);
System.out.println(this.name);
System.out.println(super.name);
}
}
package com.oop.Demo05;
//在java中,所有的类都默认直接或间接继承Object
//person 人 父类
public class Person {
//public
//protected
//default
//private
protected String name ="qi";
public void print(){
System.out.println("Person");
}
public Person() {
System.out.println("Person的无参构造");
}
// private void print(){//私有的方法无法被继承
// System.out.println("Person");
// }
}
/*
Student student = new Student();
//student.test("七");
//student.test1();
*/
重写
package com.oop.Demo05;
//继承
public class A extends B{
//重写
@Override //注解,有功能的注释
public void test(){
System.out.println("A=>TEST");
}
}
package com.oop.Demo05;
//重写都是方法的重写,和属性无关
public class B {
public void test(){
System.out.println("B=>TEST");
}
}
package com.oop.Demo05;
import com.oop.Demo05.A;
import com.oop.Demo05.B;
import com.oop.Demo05.Student;
public class Application {
//静态的方法和非静态的方法区别很大
//静态方法 方法的调用只和左边的定义的类型有关
//非静态 重写
public static void main(String[] args) {
A a = new A();
a.test();
//父类的引用指向了子类
B b = new A();//子类重写了父类的方法
b.test();
}
}
NOTE
super注意点:
1.super调用父类的构造方法,必须放在子类构造方法的第一行,
2.super必须只能出现在子类的方法或者构造方法中;
3.super和this不能同时调用构造方法!
Vs this
代表的对象不同
this:本身调用者这个对象
super:代表父类对象的应用
前提
this:没有继承也可以使用
super:只有被继承时才能被使用
构造方法
this();本类的构造
super();父类的构造
重写:需要有继承关系,子类重写父类的方法;
1.方法名必须相同
2.参数列表必须相同
3.修饰符:范围可以扩大,但不能缩小
4.抛出的异常,范围可以被缩小,但不能被扩大 ClassNotFoundException=>Exception(大)
重写:子类的方法和父类必须要一致,方法体不同
为什么需要重写
1.父类的功能,子类不一定需要,或者不一定满足
多态
package com.oop.Demo06;
public class Person {
public void run(){
System.out.println("run");
}
}
/*
多态的注意事项:
1.多态是方法的多态,属性没有多态
2.父类和子类,有联系 类型转换异常 ClassCastException
3.存在关系:有继承关系,方法需要重写,父类引用指向子类对象 father f = new Son();
1.static 方法 属于类,他不属于实例
2.final 常量
3.private 方法
*/
package com.oop.Demo06;
public class Student extends Person{
@Override
public void run() {
System.out.println("son");
}
public void eat(){
System.out.println("eat");
}
}
package com;
import com.oop.Demo06.Person;
import com.oop.Demo06.Student;
public class Application {
public static void main(String[] args) {
//一个对象的实际类型是确定的
//new Student();
//new Person();
//可以指向的引用类型就不确定了 父类的引用指向子类的类型
//Student能调用的方法都是自己的或者继承父类的
Student s1 = new Student();
//Person 父类型:可以指向子类,但是不能调用子类独有的方法(子类没重写时,默认调用父类)
Person s2 = new Student();
Object s3 = new Student();
//对象能执行那些方法,主要看对象左边的类型,和左边的关系不大
s2.run();//子类重写了父类的方法,执行子类的方法
s1.run();
((Student) s2).eat();
}
}