java貓
發布時間: 2025-01-09 19:35:13
❶ java創建一個貓類Cat。具體要求如下 急急急在線等
publicclassCat{
privatestaticStringhobby="睡覺";
privateStringname;
privateintweight;
privateintage;
publicCat(){
this("",0,0);
}
publicCat(Stringname,intweight,intage){
this.name=name;
this.weight=weight;
this.age=age;
}
publicvoidclimbTree(Stringname,intheight){
System.out.println(name+"會爬樹,能爬"+height);
}
//省略getter//setter方法.
@Override
publicStringtoString(){
return"名字:"+this.name+" "+"體重:"+this.weight+" "+"年齡:"+this.age;
}
}
publicclassMain{
publicstaticvoidmain(String[]args){
CatcatA=newCat();
CatcatB=newCat("蘭蘭",8,2);
catA.setName("花花");
catA.setWeight(10);
catA.setAge(3);
//列印貓的信息
System.out.println(catA);
System.out.println(catB);
catA.climbTree(catA.getName(),-9999);
catB.climbTree(catB.getName(),99999);
}
}
未測試
❷ java程序 一個主人有兩只寵物,一條狗一隻貓,狗叫旺財,貓叫小花,分別給寵物餵食
publicclassPerson{
publicstaticvoidmain(Stringargs[]){
Animala1=newAnimal("貓","小花","魚");
Animala2=newAnimal("狗","旺財","骨頭");
a1.eat();a2.ert();
}
}
classAnimal{
Stringspecies;
StringanimalName;
StringfoodName;
Animal(Stringspecies,StringanimalName,StringfoodName){
this.species=species;
this.animalName=animalName;
this.foodName=foodName;
}
publicvoideat(){
System.out.print("我的"+species+","+animalName+"吃了:"+foodName);
}
}
//我也才學java不到一個月,我就能理解這么多
//還可以寫繼承的。亦可以寫成多線程的。
//繼承就是把Animal類當父類,再寫兩個類繼承它。這里又可以復習多態,哈哈。
//多線程就是同事喂這倆動物。
❸ Java 貓吃魚狗吃肉
public class Cat{
public void eat(String fish){
system.out.println("吃" + fish)
}
}
public class Dog{
public void eat(String meat){
system.out.println("吃" + meat)
}
}
main(){
new Cat().eat("魚");
new Dog().eat("肉");
}
❹ java建立貓cat類和狗類,具備叫聲的方法cry(),
/*定義動物父類*/
classAnimal{
voidcry(){
System.out.println("Animalcry");
}
}
classCatextendsAnimal{
voidcry(){
System.out.println("catcry");
}
}
classDogextendsAnimal{
voidcry(){
System.out.println("dogcry");
}
}
publicclassExe2{
publicstaticvoidcry(Animalanimal){
animal.cry();
}
publicstaticvoidmain(String[]args){
Animalanimal=newAnimal();
cry(animal);
Catcat=newCat();
cry(cat);
Dogdog=newDog();
cry(dog);
}
}
熱點內容