面向对象
继承
object类
package com. oop. demo05; public class Application {
public static void main ( String[ ] args) {
Student s1 = new Student ( ) ; s1. say ( ) ; s1. setMoney ( 10 _0000_0000) ; System. out. println ( s1. getMoney ( ) ) ; }
}
package com. oop. demo05;
public class Person {
private int money ; public int getMoney ( ) {
return money; } public void setMoney ( int money) {
this . money = money; } public void say ( ) {
System. out. println ( "说了一句话" ) ; } }
package com. oop. demo05;
public class Student extends Person {
}
super详解
package com. oop. demo06; public class Application {
public static void main ( String[ ] args) {
Student s1 = new Student ( ) ; s1. test ( "wo" ) ; s1. test1 ( ) ; }
}
package com. oop. demo06; public class Person {
public Person ( ) {
System. out. println ( "无参构造器Person" ) ; } public Person ( String name) {
System. out. println ( "有参构造" + name) ; } protected String name = "Yoona" ; public void print ( ) {
System. out. println ( "Person" ) ; }
}
package com. oop. demo06; public class Student extends Person {
public Student ( ) {
super ( "ni" ) ; System. out. println ( "无参构造器Student" ) ; } private String name = "允儿" ; public void print ( ) {
System. out. println ( "Student" ) ; } public void test1 ( ) {
this . print ( ) ; super . print ( ) ; } public void test ( String name) {
System. out. println ( name) ; System. out. println ( this . name) ; System. out. println ( super . name) ; }
}
注意点一
super 注意点:
1. super 是调用父类的构造方法,必须是构造方法的第一个
2. super 必须只能出现在子类的方法或者构造方法中!
3. super 和this 不能同时调用构造方法!
Vs this :
代表的对象不同:
this :本身调用者这个对象
super :代表父类对象的应用
前提
this :没有继承的情况下也可以使用
super :只能在继承条件下次才可以使用
构造方法
this ():本类的构造
super ():父类的构造
重写
package com. oop. demo06; public class Application {
public static void main ( String[ ] args) {
A a = new A ( ) ; a. test ( ) ; B b = new A ( ) ; b. test ( ) ; }
}
package com. oop. demo06;
public class B {
public void test ( ) {
System. out. println ( "B=>test()" ) ; } }
package com. oop. demo06; public class A extends B {
@Override public void test ( ) {
System. out. println ( "A=>test()" ) ; }
}
注意点二
重写:
需要有继承关系,子类重写父类的方法!
1. 方法名必须相同
2. 参数列表必须相同
3. 修饰符:范围可以扩大,但不能缩小 public > protected > default > private
4. 抛出异常:范围可以被缩小,但不能扩大:ClassNotFoundException -- > Exception(大)重写,子类方法与父类必须一致:方法体不同!为什么需要重写:
1. 父类的功能,子类不一定需要,或者不一定满足!
Alt+ Insert :override