1.Java基础-多态性_u盘

 


向上转型:

1.Java基础-多态性_多态性_02

 

 


 

向下转型:

1.Java基础-多态性_u盘_03

 


多态性的应用:



package com.jikexueyuan.pol;


class A1{
public void tell1() {
System.out.println("A -- tell1");
}
}
class B1 extends A1{
public void tell2() {
System.out.println("A -- tell2");
}
}

class C1 extends A1{
public void tell3() {
System.out.println("A -- tell3");
}
}
//以上是比较繁琐的调用方式
class D1 extends A1{

}



public class PolDemo02 {

public static void main(String[] args) {
say(new B1()); //都是调用父类A1的代码而并没有调用自己的代码tell2
say(new C1()); //都是调用父类A1的代码而并没有调用自己的代码tell3

//以上要是有100个类,那岂不是要调用100个方法?,所以
say(new D1());
}

// public static void say(B1 b) {
// b.tell1();
// }
// public static void say(C1 c) {
// c.tell1();
// }


//以上要是有100个类,那岂不是要调用100个方法?,所以要运用到对象多态性来调用:
public static void say(A1 a) {
a.tell1();
}



}


 



instanceof关键字:

1.Java基础-多态性_u盘_04

 

 

1.Java基础-多态性_ide_05

 

 


抽象类的应用:

 

 

 



package com.jikexueyuan.pol;


abstract class Person{
private int age;
private String name;

public Person(int age,String name) {
this.age = age;
= name;
}

public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
= name;
}

public abstract void want();

}

class Student extends Person{
//学生有自己的属性score(成绩)
private int score;

public int getScore() {
return score;
}

public void setScore(int score) {
this.score = score;
}

//复写父类的抽象方法:
public Student(int age, String name,int score) {
super(age, name);
this.score = score;
// TODO Auto-generated constructor stub
}

//父类中有构造方法,所以子类也要复写构造方法:
public void want() {
System.out.println("姓名:"+ getName() + "年龄:" + getAge() +"成绩" + getScore() );

}

}

class Worker extends Person{

private int money;


public int getMoney() {
return money;
}


public void setMoney(int money) {
this.money = money;
}

//构造方法
public Worker(int age, String name,int money) {
super(age, name);
this.money = money;
// TODO Auto-generated constructor stub
}

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

}


public class AbsDemo01 {

public static void main(String[] args) {
// TODO Auto-generated method stub

Student s = new Student(10,"小明",100);
s.want();
Worker w = new Worker(30,"大明",1000);
w.want();
}

}


//不要去继承已经完成好的类


面向对象接口的使用:



package com.jikexueyuan.pol;

interface USB{
void start();
void stop();
}

class C{
public static void work(USB u) {
u.start();
System.out.println("工作中");
u.stop();
}
}

class USBDisk implements USB{

@Override
public void start() {
System.out.println("U盘开始工作");

}

@Override
public void stop() {
System.out.println("U盘停止工作");

}

}

class Printer implements USB{

@Override
public void start() {
System.out.println("打印机工作");

}

@Override
public void stop() {
System.out.println("打印机停止工作");

}

}
public class InterDemo01 {

public static void main(String[] args) {
// TODO Auto-generated method stub
C.work(new USBDisk());
C.work(new Printer());
}

}