下記の様な簡単な抽象クラスを作りました。
文字列に接頭語、接尾語を追加するクラスになります。
この例では、抽象関数doExecの戻り値は文字列型ですが、違う変数型でも返したい場合はどの様にすればよいでしょうか。
質問は、「抽象関数(doExec)の戻り値の型が定まっていない場合はどうすれば良いか」になります。
クラスの例が悪い場合は、申し訳ございません。
具体的なことを言うと、
複数の関数で行う複数の共通処理を抽象クラスで表現出来るのかなということになります。
普通にprivate関数を使っても良いのですが、こちらの方が見やすそうなので。
Sample.java
java
1package sample; 2 3public class Sample { 4 5 6 ///////////////////////////////////////////////////////// 7 // 8 // 抽象クラス 9 // 10 ///////////////////////////////////////////////////////// 11 abstract class Action { 12 13 //全処理 14 public String exec(String pre, String post) { 15 String s; 16 s = funcPre(pre); 17 s = doExec(s); //個別処理 18 return funcPost(post, s); 19 } 20 21 //共通処理 22 protected String funcPre(String pre){ 23 return pre + "_"; 24 } 25 26 //共通処理 27 protected String funcPost(String post, String s){ 28 return s + "_" + post; 29 } 30 31 //個別処理 32 abstract public String doExec(String s); //共通引数 33 } 34 35 36 ///////////////////////////////////////////////////////// 37 // 38 // クラスA 39 // 40 ///////////////////////////////////////////////////////// 41 class ActionA extends Action { 42 43 //個別変数 44 private String text; 45 46 //個別処理 47 public String doExec(String s) { 48 return s + text + "_ActionA_"; 49 }; 50 51 //クラスオブジェクト 52 public ActionA setArgs(String text) { 53 this.text = text; 54 return this; 55 } 56 } 57 58 public String funcA(String pre, String post, String text){ 59 return new ActionA().setArgs(text).exec(pre, post); 60 } 61 62 63 ///////////////////////////////////////////////////////// 64 // 65 // クラスB 66 // 67 ///////////////////////////////////////////////////////// 68 class ActionB extends Action { 69 70 //個別変数 71 private String text; 72 73 //個別処理 74 public String doExec(String s) { 75 return s + text + "_ActionB_"; 76 }; 77 78 //クラスオブジェクト 79 public ActionB setArgs(String text) { 80 this.text = text; 81 return this; 82 } 83 } 84 85 public String funcB(String pre, String post, String text){ 86 return new ActionB().setArgs(text).exec(pre, post); 87 } 88 89}
Main.java
java
1package main; 2 3import sample.*; 4 5public class Main { 6 7 public static void main(String[] args) { 8 9 Sample sample = new Sample(); 10 11 String pre = "接頭語"; 12 String post = "接尾語"; 13 String text = "ああああ"; 14 15 String s1 = sample.funcA(pre, post, text); 16 String s2 = sample.funcB(pre, post, text); 17 18 System.out.println(s1); 19 System.out.println(s2); 20 21 } 22 23}
実行結果
java
1接頭語_ああああ_ActionA__接尾語 2接頭語_ああああ_ActionB__接尾語
回答2件
あなたの回答
tips
プレビュー