Creating a Java Movie Class with Encapsulation and Details Method
Write a Java program to create a class called Movie with private instance variables title, director, and duration. Provide public getter and setter methods to access and modify these variables. Add a method called getMovieDetails() that returns a formatted string containing the movie details.
Sample Solution:
Java Code:
Movie.java
Main.java
Output:
Title: Arrival, Director: Christopher Nolan, Duration: 146 minutes
Explanation:
- Private Instance Variables: The title, director, and duration variables are declared as private to ensure encapsulation.
- Public Getters and Setters: These methods provide controlled access to the private variables.
- getTitle(): Returns the title.
- setTitle(String title): Sets the title.
- getDirector(): Returns the director.
- setDirector(String director): Sets the director.
- getDuration(): Returns the duration.
- setDuration(int duration): Sets the duration.
- getMovieDetails Method: Returns a formatted string containing the movie details.
- Main Method: Tests the functionality of the Movie class by creating an instance, setting its properties, and printing the details.
Note on Encapsulation
Encapsulation works in the above exercise by:
- Hiding Data: The private instance variables title, director, and duration are not accessible directly from outside the class.
- Controlled Access: The public getter and setter methods provide controlled access to the private variables, allowing for validation and modification when necessary.
- Data Integrity: Encapsulation helps maintain data integrity by ensuring that the internal state of the object can only be changed through well-defined methods.
For more Practice: Solve these Related Problems:
- Write a Java program where the "Movie" class prevents setting a negative duration.
- Write a Java program where the "Movie" class calculates the expected box office revenue.
- Write a Java program where the "Movie" class includes a method to filter movies by genre.
- Write a Java program where the "Movie" class tracks the number of screenings.
Go to:
Java Code Editor:
Improve this sample solution and post your code through Disqus
PREV : Creating a Java Account Class with Encapsulation and Transaction Methods.
NEXT : Creating a Java Product Class with Encapsulation and discount Method.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.