java基础之【继承】

来源:互联网 发布:美微网络电视柠檬tv 编辑:程序博客网 时间:2024/05/21 09:48

个人总结:

1、继承用于实现多态

2、继承时父类不可以转为子类,子类可以转为父类。可以理解为妻子为一个人,但一个人不一定是妻子。

3、子类的无参构造方法默认调用super()方法,即默认调用父类的无参构造函数;

      子类的有参构造函数也默认调用super()方法;

      super(str)方法时,即调用有参的构造方法;

实例如下:其中Person为父类,Wife为Person的子类,Son 为Wife的子类;

package testJava.testJC;/** * 测试继承: *  * @author sj * */public class Person {private String name;//姓名private int age; //年龄private String sex;//性别private int height;//身高Person(){System.out.println("Person...");}Person(String str){System.out.println("带参数的Person..."+str);}public String printStr(){return "名为"+name+"的是"+sex+"性";}public void setName(String name) {this.name = name;}public String getName() {return name;}public void setAge(int age) {this.age = age;}public int getAge() {return age;}public void setSex(String sex) {this.sex = sex;}public String getSex() {return sex;}public void setHeight(int height) {this.height = height;}public int getHeight() {return height;}}
package testJava.testJC;/** * 测试证明: * 1、子类可以转化为父类 * 2、父类不可以强制转化为子类 * 3、实例化子类时自动调用父类的无参构造函数 * 4、子类有参的构造函数中调用super(str),即有参的super()方法,会调用父类的含参的构造函数 * @author Administrator * */public class Wife extends Person{private String relation;Wife(){System.out.println("Wife...");}Wife(String str){//super();//默认调用父类的无参的构造函数super(str);//调用父类含参的构造函数System.out.println("带参数的Wife..."+str);}public String printStr(){setName("小徐");setSex("男");return super.printStr()+"哈哈";}public void setRelation(String relation) {this.relation = relation;}public String getRelation() {return relation;}public static void main(String[] args) {/*Person p=new Person();p.setAge(20);System.out.println("Person的年龄为"+p.getAge()+"周岁");Wife wife=new Wife();wife.setAge(30);System.out.println("妻子的年龄为"+wife.getAge()+"周岁");Person p1=new Wife();p1.setAge(40);System.out.println("Person1的年龄为"+p1.getAge()+"周岁");*///Person p2=new Person("春娇");Wife wife2=new Wife("春娇");//Person p3=new Wife("春娇");wife2.setAge(30);System.out.println(wife2.printStr());}}

package testJava.testJC;/** * 子类可以转化为父类; * 子孙类也可以转化为祖孙类; * @author Administrator * */public class Son extends Wife{Son(){System.out.println("Son...");}Son(String str){System.out.println("Son..."+str);}public static void main(String[] args) {Wife wife=new Son();Person p1=new Son();}}