简言:在Java开发的过程中,如果我们需要建立多个类,而且这些类的里面的所有方法都是一样的。
此时,我们就提出了Java三大特性之一的继承。
现在我写了三个类如下:
people类: public class people { public int age; public String name; public int height; public int id; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
worker类:
public class worker{ public int age; public String name; public int height; public int id; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
student类: public class student { public int age; public String name; public int height; public int id; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
我们不难发现上面的方法都是相同的,但是如果有几百个这样的类这就给我们后端开发工程师就带来了很大的工作量,我们Java就提出了继承。
people类: public class people { public int age; public String name; public int height; public int id; public int getAge() { return age; } public void setAge(int age) { this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public int getId() { return id; } public void setId(int id) { this.id = id; } }
student类:
public class student extends people { } worker类: public class worker extends people{ }
我们发现现在的代码已经非常简单,但是能不能实现我们这些属性的功能呢,我们还要继续写一个实现类,来实现我们的属性值。
public class test { public static void main(String[] args) { worker worker1 = new worker(); worker1.setAge(10); worker1.setHeight(175); worker1.setName("小明"); worker1.setId(455522); System.out.println("id:"+worker1.getId()); System.out.println("name:"+worker1.getName()); System.out.println("age:"+worker1.getAge()); System.out.println("height:"+worker1.getHeight()); student student1 = new student(); student1.setAge(18); student1.setHeight(180); student1.setId(20117701); student1.setName("小红"); System.out.println("id:"+student1.getId()); System.out.println("name:"+student1.getId()); System.out.println("age:"+student1.getAge()); System.out.println("height:"+student1.getHeight()); } }