面向对象之继承

来源:互联网 发布:linux控制台中文乱码 编辑:程序博客网 时间:2024/06/07 07:43

关于继承的理解,先看两个类

person类

class Person{private String name ;private int age ;public void setName(String name){this.name = name ;}public void setAge(int age){this.age = age ;}public String getName(){return this.name ;}public int getAge(){return this.age ;}};
Studet类

class Student{private String name ;private int age ;private String school ;public void setName(String name){this.name = name ;}public void setAge(int age){this.age = age ;}public void setSchool(String school){this.school = school ;}public String getName(){return this.name ;}public int getAge(){return this.age ;}public String getSchool(){return this.school ;}};

这两个类中有着较多的相似属性和方法,如果能student继承person类,将会大量节省代码量,而这个过程的实现就是继承。

一个简单的继承举例:

class Person{private String name ;private int age ;public void setName(String name){this.name = name ;}public void setAge(int age){this.age = age ;}public String getName(){return this.name ;}public int getAge(){return this.age ;}};class Student extends Person {private String school ;// 扩充的属性public void setSchool(String school){this.school = school ;}public String getSchool(){return this.school ;}};public class ExtDemo03{public static void main(String args[]){Student stu = new Student() ;//  学生stu.setName("张三") ;// 从Person继承而来stu.setAge(30) ;// 从Person继承而来stu.setSchool("西安电大") ;// 自己定义的方法System.out.println("姓名:" + stu.getName()) ;System.out.println("年龄:" + stu.getAge()) ;System.out.println("学校:" + stu.getSchool()) ;}};

该例既继承了父类的属性和方法又有自己属性与方法的扩充。

java不允许一个类同时继承多个父类,但允许多层继承,此外子类不能直接访问父类的私有操作

在子类实例化对象时,因为父类的构造优先于子类构造进行初始化,所以子类实例化操作中一般隐藏了super()方法,但也可以通过super()方法明确调用父类构造。

class Person{private String name ;private int age ;public Person(String name,int age){this.name = name ;this.age = age ;}public void setName(String name){this.name = name ;}public void setAge(int age){this.age = age ;}public String getName(){return this.name ;}public int getAge(){return this.age ;}};class Student extends Person {private String school ;// 扩充的属性public Student(String name,int age,String school){super(name,age) ;// 明确调用父类中有两个参数的构造方法this.school = school ;}public void setSchool(String school){this.school = school ;}public String getSchool(){return this.school ;}};public class ExtDemo08{public static void main(String args[]){Student stu = new Student("张三",30,"西安电大") ;//  学生System.out.println("姓名:" + stu.getName()) ;System.out.println("年龄:" + stu.getAge()) ;System.out.println("学校:" + stu.getSchool()) ;}};


0 0