Answered step by step
Verified Expert Solution
Question
1 Approved Answer
Exercise 1 : Java Generics Task 1 : Define a generic class named PairBox that can store a pair of objects of different types. The
Exercise : Java Generics
Task : Define a generic class named PairBox that can store a pair of objects of different types. The class should have two type parameters: T for the first type and U for the second type. Implement methods to set and get these objects.
Hints:
Use angle brackets to specify the type parameters in your class definition, eg class PairBox.
For setting objects, define two methods: one for each type. For getting objects, also define two methods.
Ensure your class has private variables to store the objects and use the constructor to initialize them.
Task : Implement a Generic Method
Create a utility class named BoxSwapper. Inside BoxSwapper, implement a static generic method named swap that swaps a second pair of similar elements inside a given PairBox.Due to type safety constraints, the swap method will only work with similar types stored in the PairBox.
Hints:
Remember that generics provide compiletime type safety. When defining generic classes or methods, use type parameters like where T stands for "Type".
Your method should be defined with type parameters that match those of PairBox.
Use the get and set methods of PairBox to perform the swap
Task : Implement a Generic Interface
Define a generic interface named Transformer with one type parameter.
The interface should declare a method named transform that accepts and returns an object of the generic type. Implement this interface in a class, using a specific type eg Integer or String and provide the logic to transform the input in some way.
Hints
Think about simple transformations, like negating a number or converting a string to uppercase.
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started