一、类的种类 类的多态,接口的多态
二、多态 类的多态//Person类 public abstract class Person { public abstract void doSomthing(); } //Student类 public class Student extends Person{ @Override public void doSomthing() { // TODO Auto-generated method stub System.out.println("学生学习"); } } //Teacher类 public class Teacher extends Person{ @Override public void doSomthing() { // TODO Auto-generated method stub System.out.println("老师教书"); } } //实现:因为Student和Teacher extends Person所以可以用Person指向Student和Teahcer public static void main(String[] args) { Person p1= new Student(); //A a=new B() p1.doSomthing(); Person p2= new Teacher(); p2.doSomthing(); } //如上例子,p1只能调用自己的方法和子类继承自己的方法,不能调用子类的方法。如果要调用就要向下转型 //向下转型 Person p1= new Student(); Student s1=(Student)p1; s1.test(); //A a=new B() a能调用哪些方法看自己(a)的类型,能执行哪个方法体看B接口的多态
//接口类Photo public interface Photo { public void takePhoto(); } //Sony实现Photo类 public class Sony implements Photo{ @Override public void takePhoto() { // TODO Auto-generated method stub System.out.println("sony能拍照"); } } //Iphone14Max实现Photo类 public class Iphone14Max implements Photo{ @Override public void takePhoto() { // TODO Auto-generated method stub System.out.println("14能拍照"); } } //调用 public class Demo { public static void main(String[] args) { Photo photo=new Sony(); photo.takePhoto(); Photo photo2=new Iphone14Max(); photo2.takePhoto(); } }三、注意事项 1.存在继承关系(父类和子类 接口和实现类) 2.子类重写了父类的方法 (static不能被重写 final不能被重写 private不能被重写) 3.父类引用指向子类对象 标签:Java,Photo,void,基础,多态,Person,Student,public From: https://www.cnblogs.com/YHSDDJM/p/16768392.html