From 143a3b9155a2b0f945a8c2d4c1a91d9fab2cc6c0 Mon Sep 17 00:00:00 2001 From: ybs <2606424906@qq.com> Date: Wed, 10 Aug 2022 21:51:04 +0800 Subject: [PATCH] refactor to base class --- .../com/github/hcsp/inheritance/Animal.java | 18 ++++++++++++++++++ .../java/com/github/hcsp/inheritance/Cat.java | 11 ++++------- .../java/com/github/hcsp/inheritance/Dog.java | 11 ++++------- .../java/com/github/hcsp/inheritance/Rat.java | 12 +++++------- 4 files changed, 31 insertions(+), 21 deletions(-) create mode 100644 src/main/java/com/github/hcsp/inheritance/Animal.java diff --git a/src/main/java/com/github/hcsp/inheritance/Animal.java b/src/main/java/com/github/hcsp/inheritance/Animal.java new file mode 100644 index 0000000..74cc3ab --- /dev/null +++ b/src/main/java/com/github/hcsp/inheritance/Animal.java @@ -0,0 +1,18 @@ +package com.github.hcsp.inheritance; + +public class Animal { + private String name; + + public String getName() { + return name; + } + + public Animal(String name) { + this.name = name; + } + + public void sayMyName() { + System.out.println("我的名字是" + name); + } + +} diff --git a/src/main/java/com/github/hcsp/inheritance/Cat.java b/src/main/java/com/github/hcsp/inheritance/Cat.java index f86dc38..92cbd8b 100644 --- a/src/main/java/com/github/hcsp/inheritance/Cat.java +++ b/src/main/java/com/github/hcsp/inheritance/Cat.java @@ -1,17 +1,14 @@ package com.github.hcsp.inheritance; -public class Cat { - private String name; +public class Cat extends Animal { + public Cat(String name) { - this.name = name; + super(name); } - public void sayMyName() { - System.out.println("我的名字是" + name); - } public void meow() { - System.out.println("喵" + name); + System.out.println("喵" + getName()); } } diff --git a/src/main/java/com/github/hcsp/inheritance/Dog.java b/src/main/java/com/github/hcsp/inheritance/Dog.java index 24e713a..244e273 100644 --- a/src/main/java/com/github/hcsp/inheritance/Dog.java +++ b/src/main/java/com/github/hcsp/inheritance/Dog.java @@ -1,17 +1,14 @@ package com.github.hcsp.inheritance; -public class Dog { - private String name; +public class Dog extends Animal { public Dog(String name) { - this.name = name; - } - public void sayMyName() { - System.out.println("我的名字是" + name); + super(name); } + public void wang() { - System.out.println("汪" + name); + System.out.println("汪" + getName()); } } diff --git a/src/main/java/com/github/hcsp/inheritance/Rat.java b/src/main/java/com/github/hcsp/inheritance/Rat.java index bc517d1..f9a42b4 100644 --- a/src/main/java/com/github/hcsp/inheritance/Rat.java +++ b/src/main/java/com/github/hcsp/inheritance/Rat.java @@ -1,17 +1,15 @@ package com.github.hcsp.inheritance; -public class Rat { - private String name; +public class Rat extends Animal { + public Rat(String name) { - this.name = name; - } - public void sayMyName() { - System.out.println("我的名字是" + name); + super(name); } + public void zhizhi() { - System.out.println("吱吱" + name); + System.out.println("吱吱" + getName()); } }