通过继承可以简化类的定义
java只支持单继承,不允许多重继承,可以多层继承
如:class B继承了class A,class C继承了class B,class C间接继承了class A
子类不继承父类的构造方法
在子类的构造方法中,可以使用super(参数列表)调用父类的构造方法
如果子类的构造方法中没有显式的调用父类的构造方法,也没有使用this调用重载的其它构造方法,则在产生的子类的实例对象时,系统默认调用父类无参数的构造方法
若父类不提供无参数的构造方法,则编译出错
例子:
/*
* Student.java
*
* Created on 2007-10-25, 17:46:59
*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package student;
/**
*
* @author Administrator
*/
class Person
{
protected String name;
protected int age;
protected Person(String name,int age)
{
this.name=name;
this.age=age;
}
protected Person()//注释此无参构造函数将会出错
{
}
protected void getInfo()
{
System.out.println(name);
System.out.println(age);
}
}
class Student extends Person{
/**
* @param args the command line arguments
*/
public void study()
{
System.out.println(“Studding”);
}
public static void main(String[] args) {
// TODO code application logic here
Person p=new Person();
p.name=”person”;
p.age=30;
p.getInfo();
Person p1=new Person(“person1″,31);
p1.getInfo();
Student s=new Student();
s.name=”student”;
s.age=16;
s.getInfo();
s.study();
}
}