java-继承实现学生类和老师类案例

java-继承实现学生类和老师类案例::

定义一个父类:

package day08;

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

}
子类:student

package day08;

public class StudentDemo extends PersonDemo{
        public StudentDemo(){
        	
        }
        public StudentDemo(String name,int age){
        	 super(name,age);//调用父类的有参构造方法
        }
}

子类:Teacher

package day08;

public class TeacherDemo extends PersonDemo {
     public TeacherDemo(){
    	 
     }
     public TeacherDemo(String name,int age){
    	 super(name,age);//调用父类的有参构造方法
     }
}
测试类:

package day08;

public class PersonDemoMain {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		System.out.println("******************学生类************************");
		//创建学生类对象
		StudentDemo sd = new StudentDemo();
		sd.setName("李春男");
		sd.setAge(25);
		System.out.println(sd.getName()+"--------"+sd.getAge());
		//第二种方式赋值
		StudentDemo sd2 = new StudentDemo("杨莉",25); 
		System.out.println(sd2.getName()+"--------"+sd2.getAge());
		
		System.out.println("******************老师类************************");
		//创建老师类对象
		TeacherDemo td = new TeacherDemo();
		td.setName("马金金");
		td.setAge(33);
		System.out.println(td.getName()+"----------"+td.getAge());
		//第二种方式赋值
		TeacherDemo td2 = new TeacherDemo("马金金",33);
		System.out.println(td2.getName()+"----------"+td2.getAge());
		
	}

}

输出:
******************学生类************************
李春男--------25
杨莉--------25
******************老师类************************
马金金----------33
马金金----------33

你可能感兴趣的:(java基础)