关于java继承性的一个实例


package 继承;

import java.util.Scanner;

/*
 *  定义一个人类,包括属性:姓名;包括方法:吃饭、工作。
 *	(1)根据人类,派生一个学生类,增加属性:学校、学号;重写工作方法(学生的工作是学习)。
 *	(2)根据人类,派生一个教师类,增加属性:单位、工龄;重写工作方法(教师的工作是教学)。
 * 	注意:在每个类中最好都应该有自己的属性的输入输出方法。
 * 
 */
class person {

	String name;
	
	public void input_info(){
		
		System.out.println("input person inforation:");
		System.out.println(" name ");
		Scanner sc = new Scanner(System.in);
		name = sc.next();
		System.out.println();
	
	}
	public void output_info(){
		
		System.out.println("person inforation:");

		System.out.println("person name:  "+name);
		System.out.println();
		
	}
	
	public void eat(){
		
		System.out.println("person like eat...");
		System.out.println();
	}
	
	public void work(){
		
		System.out.println( " person  " + name + " like work...");
		System.out.println();
	}
	
}

class student extends person{
	
	String number;
	String school; 
	
	public void input_info(){
		
		System.out.println("input student inforation:");
		System.out.println("name  number  school");
		
		Scanner sc = new Scanner(System.in);
		name = sc.next();
		number = sc.next();
		school = sc.next();
		System.out.println();
		
	}
	
	public void output_info(){
		
		System.out.println("student inforation:");
		System.out.println("student name:  "+name);
		System.out.println("student number:  " + number);
		System.out.println("student school:  " + school);
		System.out.println();
	}
	
	public void work(){
		
		System.out.println("student  " + name + " like study...");
		System.out.println();
	}
	
}

class techer extends person{

	String workplace;
	int age;
	
	public void input_info(){
		
		System.out.println("input techer inforation:");
		System.out.println("name  workplace  age");
		Scanner sc = new Scanner(System.in);
		name = sc.next();
		workplace = sc.next();
		age = sc.nextInt();
		System.out.println();
		
	}
	
	public void output_info(){
		
		System.out.println("techer inforation:");
		System.out.println("techer name:   "+name);
		System.out.println("techer workplace:   " + workplace);
		System.out.println("techer school:   " + age);
		System.out.println();
		
	}
	
	
    public void work(){
		
		System.out.println("techer  " + name + " like teching...");
		System.out.println();
	}

}









测试类:


package 继承;

public class person_test {

	public static void main(String[] args) {
		
		person p = new person();
		student s = new student();
		techer t = new techer();
		
		p.input_info();
		p.output_info();
		p.work();
		p.eat();
		
		
		s.input_info();
		s.eat();
		s.work();
		s.output_info();
		
		t.input_info();
		t.eat();
		t.work();
		t.output_info();
		
	}

}




测试结果:


关于java继承性的一个实例_第1张图片



关于java继承性的一个实例_第2张图片




关于java继承性的一个实例_第3张图片





你可能感兴趣的:(java学习)