首页 > 解决方案 > Java中需要的返回类型

问题描述

public Course(String cat,String breed,int age) {
    this.Cat = cat;
    this.Breed = breed;
    this.Age = age; }

此代码的返回类型是什么?

嘿大家!我以前从未学过 Java,它是必需的,所以我需要完成这个作业。请帮我解决这个非常简单的问题。非常感谢你!

标签: javareturn

解决方案


像这样:

public class Main {
   public static void main(String[] args) {
    Course cat = new Course("cat", "tabby", 7);
    if(cat.isTabby()) {
        System.out.println("Orange");

    }
    else {
        System.out.println("Other color");
    }
 }
  static class Course {
    String Cat;
    String Breed;
    int Age;
    public Course(String cat,String breed,int age) {
    this.Cat = cat;
    this.Breed = breed;
    this.Age = age; 
        }
        public boolean isTabby() {
            if(Breed=="tabby") {
                return true;
            }
            return false;
        }
    }
}   

没有返回类型,因为它是一个构造函数。构造函数用于“构造事物”,例如

Course cat = new Course("cat","tabby",6);

通常人们会在类中添加函数来对此进行操作,如上所示。


推荐阅读