程式碼:

package inheritance;

public class Inheritance 
{
    private int x;
   
    public int getX()
    {

  return x;

    }
   
    public Inheritance()
    {

  this.x=0;   //沒有傳參數的初始化

    }
   
    public Inheritance(int y)
    {

  this.x=y;  //有傳參數的初始化

    }
public static void main(String [] args
{

Inheritance t1=new Inheritance(3);

Inheritance t2=new Inheritance(3);

if(!t1.equals(t2))

System.out.println("they're not equal");

else

{

System.out.println("they're equal");

}

if(t1 instanceof Object)

System.out.println("t1's an Object");

}

public boolean equals(Object o)

{

return this.x==((Inheritance)o).getX();

}

}



顯示結果:

they're equal
t1's an Object


2.  程式碼:

class Fother
{
public void Fothersay()
{
System.out.println("today is sunday");
}
}


class Son extends Fother
{
public void Sonsay()
{
System.out.println("I want drink ice tea!");
}
}

public class Inheritance 
{
public static void main(String[] args)
{
Fother Hank=new Fother();
Hank.Fothersay();
Son Mark=new Son();
Mark.Fothersay();
        Mark.Sonsay();
}
}

顯示結果:

today is sunday

today is sunday
I want drink ice tea!



範例 3.

class Fother
{
public void Fothersay()
{
System.out.println("today is sunday");
}
}


class SonMark extends Fother
{
public void Sonsay()
{
System.out.println("I want drink ice tea!");
}
}

class SonTank extends Fother
{
public void Sonsay()
{
System.out.println("I want drink ice tea!");
}
}

public class Inheritance 
{
public static void main(String[] args)
{
SonMark grandsonHarry=new SonMark();

    //子物件

SonTank grandsonTarry=new SonTank();
//子物件
say(grandsonHarry);  
say(grandsonTarry);
}


    //父參考控制子物件

public static void say(Fother Hank)
{
Hank.Fothersay();
}

}

顯示結果:

today is sunday
today is sunday


arrow
arrow
    文章標籤
    Java
    全站熱搜
    創作者介紹
    創作者 布拉怡 的頭像
    布拉怡

    nini的部落格

    布拉怡 發表在 痞客邦 留言(0) 人氣()