[cjtoolbox name=’JavaC’]

練習問題 解答

10.9 練習問題 解答

問1

① ×:スーパークラスからはいくつでもサブクラスを作成できる。
② ×:サブクラスの継承もとになるスーパークラスは複数選べる。
③ ○
④ ×:サブクラス内でスーパークラスと同じ定義のメソッドを記述できる。
⑤ ×:必ずオーバーロードするため定義し直されなければならない。

問2

① ×:クラスYがクラスXのスーパークラスになる。
② ×:スーパークラスと同じ名前の変数をサブクラスでも定義できる。
③ ○:引数ありのコンストラクタが必要になる。
④ 〇:super()関数で呼び出しているため必要になる。
⑤ ○:スーパークラスに同じ名前のメソッドが定義されている必要はない。

問3

① A ② a1 ③ B ④ b1

⑤ A ⑥ a2 ⑦ B ⑧ b2

出力結果

[text] [クラスSampleA]の a1 のコンストラクタ [クラスSampleB]の b1 のコンストラクタ [クラスSampleA]の a2 のコンストラクタ [クラスSampleB]の b2 のコンストラクタ [/text]

問4

[python] class Books: def __init__(self,title=’未定’,price=0): self.__title = title self.__price = price print(‘本を作成しました。’) #ゲッターの定義 @property def getTitle(self): return self.__title #セッターの定義 @getTitle.setter def setTitle(self,value): self.__title = value print(‘この本のタイトルは’ + self.__title +’にしました。’) #ゲッターの定義 @property def getPrice(self): return self.__price #セッターの定義 @getPrice.setter def setPrice(self,value): self.__price = value print(‘この本の価格は’ + str(self.__price) + ‘円にしました。’) #以下にTextBooksクラスを定義しなさい class TextBooks(Books): def __init__(self,subject=’未定’): super().__init__() self.__subject = subject #ゲッターの定義 @property def getSubject(self): return self.__subject #セッターの定義 @getSubject.setter def setSubject(self,value): self.__subject = value print(‘この本の教科を’ + self.__subject + ‘にしました。’) [/python]

問5

[python] import abc class Books(metaclass=abc.ABCMeta): def __init__(self,title=’未定’,price=0): self.__title = title self.__price = price print(‘本を作成しました。’) #ゲッターの定義 @property def getTitle(self): return self.__title #セッターの定義 @getTitle.setter def setTitle(self,value): self.__title = value print(‘この本のタイトルは’ + self.__title +’にしました。’) #ゲッターの定義 @property def getPrice(self): return self.__price #セッターの定義 @getPrice.setter def setPrice(self,value): self.__price = value print(‘この本の価格は’ + str(self.__price) + ‘円にしました。’) @abc.abstractmethod def showBook(self): pass #以下にTextBooksクラスを定義しなさい class TextBooks(Books): def __init__(self,subject=’未定’): super().__init__() self.__subject = subject #ゲッターの定義 @property def getSubject(self): return self.__subject #セッターの定義 @getSubject.setter def setSubject(self,value): self.__subject = value print(‘この本の教科を’ + self.__subject + ‘にしました。’) def showBook(self): print(‘教科:’ + self.__subject) print(‘タイトル:’ + self.getTitle) print(‘価格:’ + str(self.getPrice) + ‘円’) [/python]

NEXT>> 第11章 モジュールファイルの作成