关于继承的理解,先看两个类
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 ;
}
};一个简单的继承举例:
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()) ;
}
};原文:http://blog.csdn.net/u014492609/article/details/44204513