0% found this document useful (0 votes)
26 views4 pages

Java Class Design and Implementation Guide

The document contains 5 questions related to Java classes and objects. Question 1 involves creating a Movie class with title, studio, and rating instance variables and constructors. It also involves writing a method to return only PG rated movies from an array. Question 2 involves creating an Employee class with name, salary, and methods to set/get instance variables. Question 3 involves creating Author and Book classes with related instance variables and methods. Question 4 involves creating a SavingsAccount class with a static interest rate and methods to calculate monthly interest. Question 5 provides code and asks for the output.

Uploaded by

ebrosternation
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views4 pages

Java Class Design and Implementation Guide

The document contains 5 questions related to Java classes and objects. Question 1 involves creating a Movie class with title, studio, and rating instance variables and constructors. It also involves writing a method to return only PG rated movies from an array. Question 2 involves creating an Employee class with name, salary, and methods to set/get instance variables. Question 3 involves creating Author and Book classes with related instance variables and methods. Question 4 involves creating a SavingsAccount class with a static interest rate and methods to calculate monthly interest. Question 5 provides code and asks for the output.

Uploaded by

ebrosternation
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CS224 Worksheet-2

Question 1

• The class Movie is started below. An instance of class Movie represents a film. This class
has the following three class variables:

● title, which is a String representing the title of the movie


● studio, which is a String representing the studio that made the movie
● rating, which is a String representing the rating of the movie (i.e. PG13, R, etc)

public class Movie {


private String title;
private String studio;
private String rating;
// your code goes here
}

• Write a constructor for the class Movie, which takes a String representing the title of the movie, a String
representing the studio, and a String representing the rating as its arguments, and sets the respective class
variables to these values.
• Write a second constructor for the class Movie, which takes a String representing the title of the movie and a
String representing the studio as its arguments, and sets the respective class variables to these values, while
the class variable rating is set to "PG".
• Write a method getPG, which takes an array of base type Movie as its argument, and returns a new array of
only those movies in the input array with a rating of "PG”.
• Write a piece of code that creates an instance of the class Movie with the title “Casino Royale”, the studio
“Eon Productions”, and the rating “PG13”.
Question 2

Create a class called Employee that includes three pieces of information as instance variables—a first name
(typeString), a last name (typeString) and a monthly salary (double). Your class should have a constructor
that initializes the three instance variables. Provide a set and a get method for each instance variable. If the
monthly salary is not positive, set it to 0.0. Write a test application named EmployeeTest that demonstrates
class Employee’s capabilities. Create two Employee objects and display each object’s yearly salary. Then
give each Employee a 10% raise and display each Employee’s yearly salary again.

Question 3

Write a Java class Author with following features:

• Instance variables :
o firstName for the author’s first name of type String.
o lastName for the author’s last name of type String.
• Constructor:
o public Author (String firstName, String lastName): A constructor with parameters, it
creates the Author object by setting the two fields to the passed values.

• Instance methods:

o public void setFirstName (String firstName): Used to set the first name of author.
o public void setLastName (String lastName): Used to set the last name of author.
o public double getFirstName(): This method returns the first name of the author.
o public double getLastName(): This method returns the last name of the author.
o public String toString(): This method printed out author’s name to the screen

Write a Java class Book with following features:

• Instance variables:
o title for the title of book of type String.
o author for the author’s name of type String.
o price for the book price of type double.
• Constructor:
o public Book (String title, Author name, double price): A constructor with parameters, it
creates the Author object by setting the fields to the passed values.

• Instance methods:

o public void setTitle(String title): Used to set the title of book.


o public void setAuthor(String author): Used to set the name of author of book.
o public void setPrice(double price): Used to set the price of book.
o public double getTitle(): This method returns the title of book.
o public double getAuthor(): This method returns the author’s name of book.
o public String toString(): This method printed out book’s details to the screen

Write a separate class BookDemo with a main() method creates a Book titled “Developing Java Software”
with authors Russel Winderand price 79.75. Prints the Book’s string representation to standard output (using
[Link]).

Question 4

Create class SavingsAccount. Use a static variable annualInterestRate to store the annual interest rate for all
account holders. Each object of the class contains a private instance variable savingsBalance indicating the
amount the saver currently has ondeposit. Provide method calculateMonthlyInterest to calculate the monthly
interest by multiplying the savingsBalance by annualInterestRate divided by 12 this interest should be added
to savingsBalance. Provide a static method modifyInterestRate that sets the annualInterestRate to a new
value.

Write a program to test class SavingsAccount. Instantiate two savingsAccount objects, saver1 and
saver2, with balances of $2000.00 and $3000.00, respectively. Set annualInterestRate to 4%, then
calculate the monthly interest and print the new balances for both savers. Then set the
annualInterestRate to 5%, calculate the next month’s interest and print the new balances for both
savers.
Question 5:

What is the output of the following code fragment

class Test
{
static int a1;
protected void finalize()
{
[Link]("garbage");
}
Test(int a2)
{
a1=a2;
}
Test()
{
this(23);
[Link](a1);
}
static void disp(Test s1)
{
s1.a1=25;
a1++;
}
}
public class MainClass {
public static void main(String[] args) {

Test t1=new Test();


Test.a1=25;
[Link](t1);
[Link](t1.a1);
t1=null;
new Test();
[Link]();

Common questions

Powered by AI

Common syntactic errors include incorrect method signatures or mismatched data types, such as using 'double' instead of 'String' for methods intended to return strings. To correct these, ensure method signatures accurately reflect the data type of the return value or parameters. In the 'Author' class, correcting 'public double getFirstName()' to 'public String getFirstName()' aligns the method with the intended return type, eliminating type mismatch errors and ensuring functional correctness .

Class hierarchies provide organizational benefits such as code reuse, scalability, and ease of maintenance by grouping related classes through inheritance and polymorphism, allowing derived classes to extend or override behaviors. However, challenges include increased complexity, rigidity in the hierarchy structure, and potential difficulties in debugging or understanding class interactions. Properly designed hierarchies should balance flexibility with robustness, ensuring that base classes provide a solid foundation without forcing excessive restrictions or tightly coupling derived classes .

Static methods, unlike instance methods, operate at the class level and do not require an instance to be invoked, which makes them suitable for operations not dependent on instance variables. In contrast, instance methods like those in the Book class manipulate object state and require a class instance for invocation, allowing each Book object to maintain independent state. The separation allows designers to offload global operations to static methods while preserving object-level operations for instance methods, optimizing program structure and execution .

Object-oriented programming principles can be applied to create and manage instances of a movie by defining a class, 'Movie,' with class variables such as title, studio, and rating. You can use multiple constructors to initialize these variables with different sets of inputs. For instance, a full constructor could accept all three variables, while a secondary constructor could default the rating to 'PG'. This allows flexibility in instantiation. Methods like 'getPG' further apply encapsulation and abstraction by processing and filtering movie objects based on their attributes, showcasing typical object-oriented characteristics like encapsulation and polymorphism .

In Java, if methods like 'getFirstName()' and 'getLastName()' are intended to return Strings but are typed to return doubles, the method signature should be modified from 'public double getFirstName()' and 'public double getLastName()' to 'public String getFirstName()' and 'public String getLastName()'. This aligns the return type with the expected data type, thereby resolving type mismatch issues and ensuring that the method's functionality matches its intended behavior .

Encapsulated methods in the 'Movie' class such as constructors and the 'getPG' method allow controlled modifications of object state and behavior. Constructors initialize object state upfront, ensuring integrity and consistency, while methods like 'getPG' manipulate or retrieve subsets of data based on class-internal logic, maintaining separation of concerns. By manipulating movie objects through these encapsulated interfaces, the class adheres to principles of encapsulation, enhancing modularity and maintainability .

The finalize() method in Java acts as a finalize stage for objects before they are garbage collected. Although it's not guaranteed to be called promptly or at all, if invoked, it allows resource cleanup and provides an opportunity to print messages, as seen in the Test class example with "garbage". However, relying solely on finalize() can lead to undefined behaviors and overhead, as Java's garbage collector is non-deterministic. Proper resource management should instead use try-with-resources or explicit disposal methods .

In a savings account class, using a static variable such as 'annualInterestRate' means that all instances of the class share this variable, allowing uniform changes across all objects when the static method 'modifyInterestRate' is invoked. This design choice ensures consistency in interest calculations when methods like 'calculateMonthlyInterest' are called, as all instances utilize the same interest rate, demonstrating how static variables can enforce class-wide properties and behaviors .

Constructors enhance flexibility and robustness by allowing different initialization paths for class objects. For instance, the 'Book' class can be initialized with its constructor setting title, author, and price, ensuring that the object is ready for use immediately after creation. This setup reduces the chance of uninitialized fields, promoting safe and predictable object behavior. Furthermore, a robust constructor design can accommodate both complete and partial data inputs, defaulting missing values as necessary, to support diverse initialization scenarios .

Test applications, such as 'EmployeeTest' for the Employee class, demonstrate object-oriented class capabilities by mimicking real-world use cases. They instantiate objects of the class, manipulate instance variables through provided methods, and validate outcomes, such as by calculating and displaying yearly salaries before and after raises. Such tests effectively reveal whether the class conforms to its expected behaviors under various conditions and illustrate how encapsulated interactions and data management principles are applied .

You might also like