简体   繁体   English

将对象作为参数传递给方法(Java)

[英]Passing an object as parameter to a method (Java)

Main File主文件

My class我的课

The problem I am encountering is that when I attempt to compile all my program it tells me it cant find all the variables in line 17 of my main file.我遇到的问题是,当我尝试编译所有程序时,它告诉我它无法在主文件的第 17 行中找到所有变量。

I must pass the object to the printmovieinfo method.我必须将对象传递给printmovieinfo方法。

Your printMovie method takes a Movie parameter named citizenkane (which is a bad name, since the method should be usable on any movie, not just that one).您的printMovie方法采用名为citizenkaneMovie参数(这是一个不好的名称,因为该方法应该可用于任何电影,而不仅仅是那部电影)。 To get the title and other information, you'll need to tell the program that it will be getting the information from citizenkane .要获取标题和其他信息,您需要告诉程序它将从citizenkane获取信息。 It won't read your mind.它不会读你的心。

The problem is that in the Movie class, you've provided methods for setting up that information, but no methods for getting the information out.问题是在Movie类中,您提供了设置该信息的方法,但没有提供获取信息的方法。 In addition to set methods, you'll need get methods to get the information, like:除了set方法之外,您还需要get方法来获取信息,例如:

public String getTitle() {
    return title;
}

Then, if you have a movie object named m , you can use m.getTitle() to get the title.然后,如果您有一个名为m的电影对象,您可以使用m.getTitle()来获取标题。 m.title won't work because the title field in the Movie is private , meaning it isn't visible to any other classes. m.title不起作用,因为Movietitle字段是private ,这意味着它对任何其他类不可见。 Use this syntax with your citizenkane parameter to retrieve the title and other information.将此语法与您的citizenkane参数结合使用以检索标题和其他信息。

use the reference citizenkane in printMovieInfo() , but notice that all the variables in your class Movie are private so you can't access them in printMovieInfo() .printMovieInfo()使用引用citizenkane ,但请注意类Movie中的所有变量都是private因此您无法在printMovieInfo()访问它们。 so either make them public or provide public getters for them and use them in printMovieInfo()所以要么让它们public ,要么为它们提供公共 getter 并在printMovieInfo()使用它们

Write 'get' methods in your Movie class.在 Movie 类中编写“get”方法。 These are just simple functions that return your private variables.这些只是返回私有变量的简单函数。 Then access them in your main class with citizenkane.getTitle(), and so on.然后使用citizenkane.getTitle() 在您的主类中访问它们,依此类推。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM