インターフェースの学習でデモを実行してみたのですが、
コードを部分的に抽象的に書くと
java
1for(){ 2 if(){ 3 print() 4 println() 5 }else{ 6 throw Exception 7 } 8}
としていて、if分の判定は、0番目の要素はtrueで1番目の要素はfalseです。
print -> println -> throw の順番で呼び出されると想定していたのですが、
なぜか print -> throw(前部分) -> println -> throw(後部分)のような順番で出力されました。
なぜでしょうか。
java
1for(){ 2 if(){ 3 print() 4 println() 5 print() 6 }else{ 7 throw Exception 8 } 9}
のようにすると期待通りの表示になります。
(上の関数等は状況がわかる程度に省略しています。)
☟実際のコード
プログラムの概要
Interface Soundable{ void sound();} ... 鳴ける生き物につけるインターフェース Class Being ... 生物(抽象)クラス Class Dog extends Being implements Soundable , Class Beatle extends Being...実装クラス Class Main ... 実行クラス
Java
1package main; 2 3import java.util.ArrayList; 4import java.util.List; 5 6import Objects.Beatle; 7import Objects.Being; 8import Objects.Dog; 9import interfaces.Soundable; 10 11public class Main { 12 13 public static void main(String[] args) throws Exception { 14 // TODO Auto-generated method stub 15 List<Being> beings = new ArrayList<Being>(); 16 beings.addAll(List.of(new Dog("Vertex"), new Beatle("Alex"))); 17 18 for (Being being : beings) { 19 if(being instanceof Soundable) { 20 System.out.print(being.getName() + " "); 21 ((Soundable) being).Sound(); 22 23 //これをいれると直る(しっかり改行される) 24 //System.out.print(""); 25 }else { 26 //System.out.println(being.getName() + " cannot make a sound."); 27 throw new Exception(being.getName() + " cannot make a sound."); 28 } 29 } 30 } 31 32} 33
↓標準出力
Vertex Exception in thread "main" Wan Wan java.lang.Exception: Alex cannot make a sound. at main.Main.main(Main.java:24)
java
1package interfaces; 2 3public interface Soundable { 4 public void Sound(); 5}
java
1package Objects; 2 3public abstract class Being { 4 protected String type = "Being"; 5 protected String name = ""; 6 7 public String getType() { 8 return type; 9 } 10 public String getName() { 11 return name; 12 } 13 14}
java
1package Objects; 2 3import interfaces.Soundable; 4 5public class Dog extends Being implements Soundable{ 6 7 8 public Dog(String name){ 9 type = "Dog"; 10 this.name = name; 11 } 12 13 @Override 14 public void Sound() { 15 // TODO Auto-generated method stub 16 System.out.println("Wan Wan"); 17 } 18 19}
java
1package Objects; 2 3import interfaces.Soundable; 4 5public class Dog extends Being implements Soundable{ 6 7 8 public Dog(String name){ 9 type = "Dog"; 10 this.name = name; 11 } 12 13 @Override 14 public void Sound() { 15 // TODO Auto-generated method stub 16 System.out.println("Wan Wan"); 17 } 18 19}
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/02/02 03:56