Java面向对象多态性

package com.chenglei.Pol;


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()");
	}
}


abstract class Person{
	private int age;
	private String name;
	public void setAge(int age){
		this.age = age;
	}
	public int getAge(){
		return age;
	}
	public void setName(String name){
		this.name = name;
	}
	public String getName(){
		return name;
	}
	
	public Person(int age, String name){
		this.age = age;
		this.name = name;
	}
	
	public abstract void want();
	
	
}

class Student extends Person {
	private int score;
	
	public void setScore(int score){
		this.score = 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 salary;
	public void setSalary(int salary){
		this.salary = salary;
	}
	public int getSalary(){
		return salary;
	}
	
	public Worker(String name, int age, int salary){
		super(age,name);
		this.salary = salary;
	}
	
	public void want(){
		System.out.println("姓名:"+getName()+" 年龄:"+getAge()+" 成绩:"+getSalary());

	}
}



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{
	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 PolDemo {

	public static void main(String[] args) {
		//向上转型
		B b = new B();
		A a = b;
		a.tell1();//tell1()重写的
		a.tell2();
		
		//向下转型
		A a2 = new B();
		B b2 = (B)a2;
		b2.tell1();
		b2.tell2();
		b2.tell3();
		
		
		/*
		 * instanceof
		 * 判断是否是其类的一个实例
		 */
		A a3 = new A();
		System.out.println(a3 instanceof A);
		System.out.println(a3 instanceof B);
		
		A a4 = new B();
		System.out.println(a4 instanceof A);
		System.out.println(a4 instanceof B);
		
		Student stu = new Student(12,"xiaoming",78);
		stu.want();
		
		Worker worker = new Worker("xiaohua",23,80);
		worker.want();
		
		
		C.work(new USBDisk());
		C.work(new Printer());
		
	}

}

你可能感兴趣的:(Java面向对象多态性)