定義一個長方形,求它的周長和面積。用面向?qū)ο蟮姆椒ā?
?
class 長方形 {
????int
長;int
寬;
????int 周長()
????{
????????return 2*(長+寬);
????}
????int 面積()
????{
????????return
長*寬;
????}????????
????public
static
void main(String[] args)
????{
????????長方形 chang1=new 長方形();
????????長方形 chang2=new 長方形();
????????chang1.長=10;
????????chang1.寬=5;
????????System.out.println("周長="+chang1.周長());
????????System.out.println("面積="+chang1.面積());
????????chang2.長=20;
????????chang2.寬=8;
????????System.out.println("周長="+chang2.周長());
????????System.out.println("面積="+chang2.面積());
????}
}
public
class Animal
{
????int
height;
????int
weight;
????void animal()
????{
????????System.out.println("Animal constract");
????}
????void eat()
????{
????????System.out.println("Animal eat");
????}
????void sleep()
????{
????????System.out.println("Animal sleep");
????}
????void breathe()
????{
????????System.out.println("Animal breathe");
????}
}
/*
* 理解繼承是理解面向?qū)ο蟪绦蛟O(shè)計的關(guān)鍵
* 在java中,通過關(guān)鍵字extends繼承一個已有的類,被繼承的類稱為父類(超類,基類),新的類稱為子類(派生類)。
* * 在java中,不允許多繼承
*/
class Fish extends Animal
{
????void fish()
????{
????????
????????System.out.println("fish constract");
????}
????void breathe()
????{
????????//super.breathe();
????????//super.height=40;
????????System.out.println("fish boo");
????}
}
class Integration
{
????public
static
void main(String[]args)
????{
????????//Animal an=new Animal();
????????Fish fh=new Fish();
????????//an.breathe();
????????//fh.height=30;
????????fh.breathe();
????????
????}
}
/*
*在子類當(dāng)中定義一個與父類同名,返回類型,參數(shù)類型均一致的方法,稱為方法的覆蓋
*方法的覆蓋發(fā)生在子類和父類之間。
*調(diào)用父類的方法使用super
*/
/*特殊變量super,提供了父類的訪問
* 可以使用super訪問被父類被子類隱藏的變量或覆蓋的方法
* 每個子類構(gòu)造方法的第一句,都是隱藏的調(diào)用super(),如果父類沒有這種形式的構(gòu)造函數(shù),那么在編譯器中就會報錯。
*
*
*
*/