快學scala第6章習題——物件相關
1.編寫一個conversion物件,加入inchestoCentimeters,gallonstoliters,milestoKilometers方法
object Conversions{
def inchesToCentimeters():Unit={
println("Hello World");
}
def gallonsToLiters():Unit={
}
def milesToKilometers():Unit={
}
}
物件的呼叫方式
Conversions.inchesToCentimeters ();
2.前一個練習不是很面向物件,提供一個超類UnitConversion並定義擴充套件該超類的inchestoCentimeters,gallonstoliters,milestoKilometers的方法
object InchesToCentimeters extends UnitConversion{
override def inchesToCentimeters() {}
}
object GallonsToLiters extends UnitConversion{
override def gallonsToLiters() {}
}
object MilesToKilometers extends UnitConversion{
override def milesToKilometers() {}
}
abstract class UnitConversion{
def inchesToCentimeters():Unit;
def gallonsToLiters():Unit
def milesToKilometers():Unit
}
3.定義一個擴充套件自java.awt.Point的Origin物件,為什麼說這不是一個好方法?
因為 public java.awt.Point getLocation();返回的物件是原始Point物件,而不是繼承Origin物件本身,而要返回Origin物件就需要Origin類
object Origin extends java.awt.Point{
override def getLocation():java.awt.Point=super.getLocation();
}
想返回origin物件的,需要用到類
class Origin extends java.awt.Point{
def this(x:Int,y:Int){
this();
this.x=x;
this.y=y;
}
override def getLocation():Origin = {
this;
}
}
4.定義一個Point類,和伴生物件,使我們可以通過Point(3,4)的形式來直接構造例項
class point(var x:Int,var y:Int){
def show="x= "+x+ " , "+"y= "+y;
}
object point{
//不能打括號,因為沒返回引數,返回的是Unit型別
def apply(x:Int,y:Int)=new point(x,y);
}
5.編寫一個scala應用程式,使用App特質,以反序列印命令列引數,用空格隔開,舉例來說,scala Reverse Hello World應該打印出world hello。命令列引數和java的新增方式一樣
override def main(args:Array[String]){
for(i<- (0 until args.length).reverse){
print(args(i)+" ");
}
}
6.編寫一個撲克牌4種花色的列舉,讓其toString方法返回4種撲克符號,直接使用print列印即可
object cardmark extends scala.Enumeration{
type cardmark = Value;
val hongtao=Value("♥");
val meihua=Value("♣");
val heitao=Value("♠");
val fangkuai=Value("♦");
}
7.實現一個函式,檢查某張牌的花色是否為紅桃
def judgeColor(Color:cardmark.Value):Boolean={
if(Color==cardmark.hongtao||Color==cardmark.fangkuai){
true;
}else{
false;
}
}
8.編寫一個列舉,描述RGB立方體的8個角,ID使用顏色值(例如:紅色:0xff0000)
RGB的立方體的八個角分別為(1,0,0)=(0xff0000),(0,1,0)=(0x00ff00),(0,0,1)=(0x0000ff),(1,1,0)=(0xffff00),(1,1,1)=(0xffffff),(1,0,1)=(0xff00ff),(0,1,1)=(0x00ffff),(0,0,0)=(0x000000),value引數為ID,名稱,如果ID預設就在前項基礎上+1,如果ID都預設,就按順序從0開始依次+1,名稱預設就和欄位名稱一樣。
列舉定義如下:
object RGB extends Enumeration{
val White=Value(0xffffff,"White");
val Red=Value(0xff0000,"Red");
val Green=Value(0x00ff00,"Green");
val Blue=Value(0xf0000ff,"Blue");
val Yellow=Value(0xffff00,"Yellow");
val Black=Value(0x000000,"Black");
val Cyan=Value(0x00ffff,"Cyan");
val MAGENTA=Value(0xff00ff,"Magenta");
}