[JAVA] Upcast, Dowcast and Constructor

import java.util.*;

interface Sample{ //定数はインターフェースに定義できるよ public final static int num=10; // Abstract method public abstract is created automatically public abstract void hoge();

}

interface Test{ //定数はインターフェースに定義できるよ public final static int num=10; // Abstract method public abstract is created automatically public abstract void exe();

}

//多重実現 class SampleImp implements Sample,Test{ public void hoge(){

}

public void exe(){
    
}

}

class A{

public int i=10;

 A(int i){

System.out.println ("Constructor for A"); }

void test(){
    System.out.println("void test A");
}

void test2(){
    System.out.println("void test2 A");
}

}

class B extends A{

public int i=100;

B(){
    super(100);
    System.out.println("Bkon");
}

@Override
void test(){
    System.out.println("void test B");
}

 void test3(){
    System.out.println("void test3 B");
}

}

public class Main { public static void main(String[] args) throws Exception {

//キャストアップの例 // When casting from a subclass to a super, the closer 10 variable is used and the method is overridden //れたテスト2と出力、Bのメソッドは上書きされていないので使おうとするとエラー

// Note: The superclass is prioritized for field variables, and the subclass is prioritized for methods. A b= new B();

    b.test();
    //b.test3();

// Example of downcast ↓ Only the upcast can be returned. You can also use instanceof as a method to check.

// Upcast (implicit) A bb= new B();

// Downcast (explicit) B bbb = (B)bb;

// SubClass methods bbb.test(); bbb.test3();

}

}

Recommended Posts

Upcast, Dowcast and Constructor
constructor