1、父类
package com.wyq.study;
public class Animal {
private int age;
public void setAge(int age){
this.age = age;
}
public int getAge(){
return age;
}
public Animal(){
System.out.println("这里是无参构造");
}
public Animal(int age){
this.age = age;
System.out.println("这里是带参构造方法");
}
public void introduce(){
System.out.println("这里是动物的自我介绍。");
}
}
2、子类一
package com.wyq.study;
public class Bird extends Animal{
private double weight;
public double getWeight() {
return weight;
}
public void setWeight(double weight) {
this.weight = weight;
}
public Bird(double weight) {
super();
this.weight = weight;
}
public Bird() {
super();
}
public Bird(int age,double weight) {
super(age);
this.weight = weight;
}
@Override
public void introduce() {
super.introduce();
System.out.println("这里是鸟类的自我介绍"+super.getAge()+"\t"+this.getWeight());
}
public void swimming(){
System.out.println("鸟类会游泳");
}
}
3、子类二
package com.wyq.study;
import javax.swing.plaf.synth.SynthScrollBarUI;
public class Fish extends Animal{
private String color;
public String getColor() {
return color;
}
public void setColor(String color) {
this.color = color;
}
public Fish(String color) {
super();
this.color = color;
System.out.println("这里是鱼类的带参构造");
}
public Fish() {
super();
}
@Override
public void introduce() {
System.out.println("这里是鱼类的自我解的接受啊"+this.color+"\t"+super.getAge());
super.introduce();
}
public void fly(String place){
System.out.println("鱼类在"+place+"飞,他的颜色是:"+this.color);
}
}
4、测试类
package com.wyq.study;
public class TestAnimal {
public static void main(String[] args) {
Bird br = new Bird(12,23.6);
br.introduce();
br.swimming();
Fish fs = new Fish("黄色");
fs.fly("水里");
}
}
5、总结
1)先写父类,再写子类
2)子类继承父类
3)写公有的取值赋值方法get,set方法
4)写构造方法
5)写普通方法
6)方法的重新
7)在带参的构造方法中,使用this.属性和this.set属性,使用super调用父类的属性