创建一个影片类,属性参考豆瓣网站.https://movie.douban.com/subject/35242872/.将属性私有化提供公共方法来访问私有属性,同时创建这个类对象,给属性赋值,并输出这
时间: 2024-09-21 22:04:46 浏览: 39
高级java笔试题-books:https://github.com/justjavac/free-programming-books-zh_
创建一个电影类,我们可以参考豆瓣电影的信息结构。例如,可以考虑以下属性:电影ID、标题、导演、演员、评分、上映年份和简介。为了保护这些信息不直接暴露在外,我们将它们设置为私有变量,并提供公有的getter方法来获取这些数据。
```java
public class Movie {
// 私有属性
private int movieId;
private String title;
private String director;
private String[] actors;
private double rating;
private int year;
private String summary;
// 构造函数
public Movie(int movieId, String title, String director, String[] actors, double rating, int year, String summary) {
this.movieId = movieId;
this.title = title;
this.director = director;
this.actors = actors;
this.rating = rating;
this.year = year;
this.summary = summary;
}
// 公共方法获取私有属性
public int getMovieId() {
return movieId;
}
public String getTitle() {
return title;
}
public String getDirector() {
return director;
}
public String[] getActors() {
return actors;
}
public double getRating() {
return rating;
}
public int getYear() {
return year;
}
public String getSummary() {
return summary;
}
// 示例:创建并初始化电影对象
public static void main(String[] args) {
String[] actors = {"张三", "李四"};
Movie film = new Movie(35242872, "肖申克的救赎", "弗兰克·德拉邦特", actors, 9.6, 1994, "两个男人在监狱中的友情故事");
System.out.println("电影ID: " + film.getMovieId());
System.out.println("标题: " + film.getTitle());
System.out.println("导演: " + film.getDirector());
System.out.println("主演: " + Arrays.toString(film.getActors()));
System.out.println("评分: " + film.getRating());
System.out.println("上映年份: " + film.getYear());
System.out.println("简介: " + film.getSummary());
}
}
```
阅读全文