LoginSignup
0

ポリモーフィズム

Last updated at Posted at 2022-12-24

説明

実際に動作しているインスタンスを、インスタンスの元となった型とは異なる型で扱える仕組みのことを指す。条件は、継承、あるいは実現の関係にある場合のみである。
public interface A {
    public void start();
}
public class B implements A {
    public void start(){
        System.out.println("B")
    }
}
public class C extends B {
    public void start(){
        System.out.println("C");
    }
}
public class Main {
	public static void main(String[] args) {
        A b = new B();
        A c = new C();
        b.start();//B
        c.start();//C
	}
}	
public class A {
	int test;
}
public class B extends A {
	int test;
}
public class C extends B {
	int test;
}
public class D extends C {
	int test;
}
public class Main {
	public static void main(String[]args) {
		A[]e= {
			new A(),
			new B(),
			new C(),
			new D()
		};
		for(A d : e) {
			d.test += 50;
			System.out.println(d.test);
		}
	}
}

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
0