类和对象:继承extends练习
扩充
//继承的练习:扩充,继承。
class Itme{//物品类
String name;
int price;
}
//***extends:扩充,继承。继承写法***
class Weapon extends Itme{
int sal;
}
public class Week_55 {
/*public class Weapon{//不继承Item,从新设计属性
String name;
int price;
int sal;
}*/
public static void main(String args[]) {
Weapon infEdge = new Weapon();
infEdge.name = "黑切";
infEdge.price = 1200;
infEdge.sal = 3600;
System.out.println(infEdge.sal);
}
}
优点 :
A:提高了代码的复用性
B:提高了代码的维护性
C:让类与类之间产生了关系,是多态的前提
/*
继承练习:extends
A:提高了代码的复用性
B:提高了代码的维护性
C:让类与类之间产生了关系,是多态的前提
*/
class Person{//人类
public void eat() {
System.out.println("吃饭");
}
public void sleep() {
System.out.println("睡觉");
}
}
class Student extends Person{}//继承人类
class Teacher extends Person{}//继承人类
public class ExtendsDemo {
public static void main(String[] args) {
Student s = new Student();
s.eat();
s.sleep();
Teacher t = new Teacher();
t.eat();
t.sleep();
}
}
特点:A:只支持单继承,不支持多继承
例:class Son extends Father,GrandFather{}//这是错误的
B:Java支持多层继承(继承体系)
class GrandFather{
public void show() {
System.out.println("爷爷");
}
}
class Father extends GrandFather{
public void show2() {
System.out.println("爸爸");
}
}
class Son extends Father{}//多层继承
public class ExtendsDemo2 {
public static void main(String[] args) {
Son s = new Son();
s.show();
s.show2();
}
}