子类继承父类,再调用子类

  • 程序员 - 子类

  • 继承自人类

  • 在人类的基础上进行扩展 ```java package Test12_Demo.Demo03;/*

    @create 2020—11—30—10:41 */

import Test12_Demo.Demo03.Person;

public class Coder extends Person {

  1. public String name;
  2. public void Coding() {
  3. System.out.println("Hello Word!");
  4. }

}

  1. 父类:
  2. ```java
  3. package Test12_Demo.Demo03;/*
  4. @create 2020--11--30--10:40
  5. */
  6. public class Person {
  7. private String name;
  8. private int age;
  9. public Person() {
  10. }
  11. public void eat() {
  12. System.out.println("one day day only just eat");
  13. }
  14. public void sleep() {
  15. System.out.println("sleeping");
  16. }
  17. public String getName() {
  18. return name;
  19. }
  20. public void setName(String name) {
  21. this.name = name;
  22. }
  23. public int getAge() {
  24. return age;
  25. }
  26. public void setAge(int age) {
  27. this.age = age;
  28. }
  29. }

调用子类:

  1. package Test12_Demo.Demo03;/*
  2. @create 2020--11--30--10:29
  3. */
  4. import Test12_Demo.Demo03.Coder;
  5. public class ExtendsDemo {
  6. public static void main(String[] args) {
  7. //创建子类对象
  8. Coder c = new Coder();
  9. //子类继承了父类的属性 - 只能通过get/set方法处理
  10. c.setName("詹姆斯.高斯林");
  11. c.setAge(65);
  12. System.out.println(c.getName() + "," + c.getAge());
  13. //子类继承了父类的方法
  14. c.eat();
  15. c.sleep();
  16. //子类访问自己的方法
  17. c.Coding();
  18. }
  19. }