JAVA改写成用constructor方法

查看:96
本文介绍了JAVA改写成用constructor方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

我已经写好程式码了 但不知道如何利用 "constructor" 去改写程式码
总共显示出
1出生日期
2.移动
3.品种
4.名子

动物或狗在被創造出來時时,如何用建构式?
求解改写程式码

class Animal{
    
//      public Animal(String birthday ) {
//          this.birthday = birthday ;
//          Move();
//      }
//      
        String birthday;
      
        void SetBirthday(String birthday){
            this.birthday = birthday ;
        }
    
          void Show(){
            System.out.println("birthday:" + birthday);
        }
          
          
          void Move(){
              System.out.println("move ");
        }
}


    
    
    class Dog extends Animal{

        private String name;
        private String kind;
        
        void SetName(String name){
            this.name = name;
        }
        
        void SetKind(String kind){
            this.kind = kind ;
        }
        
        void Show(){  
           super.Show();   //birthday
            System.out.println("petname:"+name);
            System.out.println("petkind:"+kind);
        }

}

  public class main{
        public static void main(String[] args){
          
            Dog dog = new Dog();
            dog.SetBirthday("20060512");
            dog.SetName("bread");
            dog.SetKind("Golden Retriever");  
            dog.Show();
              dog.Move();  
              
              Dog dog2 = new Dog();
            dog2.SetBirthday("20070512");
            dog2.SetName("Doge");
            dog2.SetKind("Maltese");  
            dog2.Show();
              dog2.Move();  
          
              Animal anAnimal = new Animal();
            anAnimal.Move();
    
        }
    }

解决方案

class Animal {
    String birthday;
    Animal(String birthday) {
        this.birthday = birthday;
    }
    //...
}
class Dog extends Animal {
    String name;
    String kind;
    Dog(String birthday, String name, String kind) {
        super(birthday);
        this.name = name;
        this.kind = kind;
    }
    //...
}
public class Main() {
    public static void main(String[] args) {
        Dog dog = new Dog("20060512", "bread", "Golden Retriever");
        dog.show();
        dog.move();
        //...
    }
}

这篇关于JAVA改写成用constructor方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆