JAVA面向对象的多态性

时间:2022-03-14 11:47:19

JAVA面向对象的多态性

01——向上转型和向下转型及简单应用

class A{

public void tell1(){
System.out.println("A_tell1");
}

public void tell2(){
System.out.println("A_tell2");
}
}
class B extends A{
public void tell1(){
System.out.println("B_tell1");
}

public void tell3(){
System.out.println("B_tell3");
}
}


public class PolDemo01 {
public static void main(String[] args) {
//B b = new B();
//A a = b;
//up
A a = new B();
a.tell1();
a.tell2();
//down
A a1 = new B();
B b = (B)a1;
//B b = new B();
b.tell1();
b.tell2();
b.tell3();

System.out.println("----");
say(new B());
say(new A());
}

public static void say(A a){
a.tell1();
}
}


打印结果:

B_tell1
A_tell2
B_tell1
A_tell2
B_tell3
----
B_tell1
A_tell1


02——instanceof的使用

public static void main(String[] args) {
A a = new A();
System.out.println(a instanceof A);
System.out.println(a instanceof B);
A a1 = new B();
System.out.println(a1 instanceof A);
System.out.println(a1 instanceof B);
}

打印结果:

true
false
true
true



03——抽象类的应用

abstract class Person{
private int age;
private String name;
public Person(int age ,String name){
this.age = age;
this.name = name;
}
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 abstract void want();
}
//通过抽象类的方法 继承了getAge()等一系列方法。
//使得子类拥有了父类的属性和方法。
class Student extends Person{
private int score;
public int getScore(){
return score;
}


public Student(int age, String name,int score) {
super(age, name);
this.score = score;
}
public void want(){
System.out.println("姓名: "+getName()+" 年龄:"+getAge()+" 成绩: "+getScore());
}

}
class Worker extends Person{
private int money;
public int getMoney(){
return money;
}

public Worker(int age, String name,int money) {
super(age, name);
this.money = money;
}

public void want() {
System.out.println("姓名: "+getName()+" 年龄:"+getAge()+" 工资: "+getMoney());
}

}


public class AbsDemo01 {

public static void main(String[] args) {
Student s = new Student(10, "小白", 100);
s.want();
Worker w = new Worker(30, "大白", 3000);
w.want();

}

}

打印结果:

姓名: 小白  年龄:10  成绩: 100
姓名: 大白  年龄:30  工资: 3000



04——面向对象接口的使用

interface USB{
void start();
void stop();
}
//都得按照USB的这个模板来运行
class Computer{
public static void work(USB u){
u.start();
System.out.println("working");
u.stop();
System.out.println("stop");
}
}
class USBDisk implements USB{
public void start(){
System.out.println("U盘开始工作");
}
public void stop(){
System.out.println("U盘停止工作");
}
}
class Printer implements USB{
public void start(){
System.out.println("打印机开始工作");
}
public void stop(){
System.out.println("打印机停止工作");
}
}

public class InterDemo01 {

public static void main(String[] args) {
Computer.work(new USBDisk());
Computer.work(new Printer());
}

}

打印结果:

U盘开始工作
working
U盘停止工作
stop
打印机开始工作
working
打印机停止工作
stop


——————记录学习过程 日后可能会用到