I have one class that declares an enumeration type as:
public enum HOME_LOAN_TERMS {FIFTEEN_YEAR, THIRTY_YEAR};
Is this type usable in another class? I'm basically trying to complete a homework assignment where we have two types of loans, and one loanManager class. When I try to use the HOME_LOAN_TERMS.THIRTY_YEAR in my loanManager class that does not extend or implement the loan class, I get an error saying it 'cannot find symbol HOME_LOAN_TERMS.' So I did not know if my loanManager class needed to implement the two different loan classes. Thanks.
I'm currently working on this so I know it's not complete, but here is where I tried to use it:
import java.util.ArrayList;
public class AcmeLoanManager
{
public void addLoan(Loan h)
{
loanArray.add(h);
}
/*
public Loan[] getAllLoans()
{
}
public Loan[] findLoans(Person p)
{
}
public void removeLoan(int loanId)
{
}
*/
private ArrayList<Loan> loanArray = new ArrayList<Loan>(5);
public static void main(String[] args)
{
AcmeLoanManager aLoanManager = new AcmeLoanManager();
Person aPerson = new Person("Crystal", "Twix", "619-111-1234", "ct#yahoo.com");
HomeLoan aHomeLoan = new HomeLoan(aPerson, 400000, 5, HOME_LOAN_TERMS.THIRTY_YEAR);
aLoanManager.addLoan(aHomeLoan);
}
}
You have to specify the type:
HOME_LOAN_TYPES type = HOME_LOAN_TYPES.FIFTEEN_YEAR;
By the way, don't use this naming convention for enums. Use the same camel case you do for classes so:
public enum HomeLoanType {
FIFTEEN YEAR,
THIRTY_YEAR
}
If you don't want to specify the type you can do a static import:
import static package.name.HomeLoanType.*;
...
HomeLoanType type = FIFTEEN_YEAR;
Lastly, one of the best things about Java enums is they can have state and behaviour. For example:
public enum HomeLoanType {
FIFTEEN YEAR(15),
THIRTY_YEAR(30);
private final int years;
HomeLoanType(int years) {
this.year = years;
}
public int getYears() {
returns years;
}
}
Yes, since it's public you can use it from another class.
If it's in your Loan class you write Loan.HOME_LOAN_TERMS.FIFTEEN_YEAR to refer to it from a different class.
Related
I have two similar class objects. I have a couple of methods for the first class object wich I also want to reuse for my second class object but I'm not sure how and I don't want to write duplicate methods.
I extracted and simplified an example to show how i think.
first class
public class FirstClass {
int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
...
}
Second class
public class SecondClass {
int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
...
}
Third class
public class Main {
public static void main(String[] args) {
FirstClass firstClass = new FirstClass();
firstClass.setNumber(5);
SecondClass secondClass = new SecondClass();
secondClass.setNumber(5);
numberIsFive(firstClass);
numberIsFive(secondClass);
}
public void numberIsFive(Object myObject){
if(myObject instanceof FirstClass){
myObject = (FirstClass)myObject;
}else if(myObject instanceof SecondClass){
myObject = (SecondClass)myObject;
}
if(myObject.getNumber() == 5){
System.out.println("is five");
}else{
System.out.println("is not five");
}
...
}
}
and no numberIsIFive(firsclass.getNumber()) is not an option since the methods I use have much more validations.
thanks in advance
For this case that might be "over-engineering", but in general you would look towards composition here, like:
interface IntValueHolder {
int getNumber();
void setNumber(int value);
}
class IntValueHolderImpl implements IntValueHolder { ...
And then you would "drop" the code that you currently have in both of your classes, and instead, both classes would (somehow) have an instance of IntValueHolder.
In your case, it might be more appropriate to simple have your two classes implement that "common" interface IntValueHolder - to at least avoid that repeated instanceof calls and downcast (down to a specific class).
Edit: of course, another option would be to use inheritance here - make your two classes derive from some base class that provides this behavior. But using inheritance just to avoid code duplication is most of the time a bad idea. Classes inherit from each other because that makes "sense" in the underlying model, not to save a line of code.
Before continuing I recommend you to read about it and other object oriented programming concepts by yourself.
Focusing on this particular case, you should create a base class such as
public class BaseClass {
int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
}
Which includes all common fields and methods of your FirstClass and SecondClass. Then remove those methods from your two current classes, and just create them as public class FirstClass extends BaseClass to give them BaseClass functionality.
Finally, you'd have to change your validation method, to only accept objects that belong to your base class by making it like this public void numberIsFive(BaseClass myObject) (as a general rule you'll have much less errors by accepting a specific class in a method, rather than accepting any old object).
Edit: Other answerers are correct and Inheritance is also a valid solution. Which one you use would depend on what makes more sense in the context of your application.
You should create an interface and apply it in both classes, then make your validation method receive an interface instead of an Object
Example:
public interface Number {
int get();
void set(int n);
}
Then your classes will look like this:
public class FirstClass implements Number {
int number;
#Override
public int get() {
return number;
}
#Override
public void set(int n) {
this.number = n;
}
}
And your validation method receives a Number:
public void numberIsFive(Number myNumber){
...
}
I need to be able to understand which method (listed below) would be more beneficial to use in a Java environment.
My problem is thus: I am creating a class in which I am going to use for holding multiple objects of the same type, however if I want to use it in the future, I want to be able to pass different objects to a different instance of Array2D. Its name is Array2D and contains private instance variables named rows and columns. However, what I want to do is be able to pass any object (when you instantiate it) to this class and be able to return the same type with methods inside of Array2D.
Method 1
Create Array2D using generic types. https://docs.oracle.com/javase/tutorial/java/generics/types.html
Method 2
Create a superclass that can be extended from to pass straight into Array2D.
Example of Method 1:
public class Array2D<T> {
private int rows;
private int columns;
private T[] t;
public Array2D(int rows, int columns) {
this.rows = rows;
this.columns = columns;
}
public T[] returnSomething() {
return t;
}
}
Example of Method 2:
Arrayable.java
public class Arrayable {
//all of my variables for arrayable class
}
Example.java
public class Example extends Arrayable {
//more stuff
}
Array2D.java
public class Array2D {
private int rows;
private int columns;
private Arrayable[] arrayable;
public Array2D(Arrayable[] arr) {
this.arrayable = arr;
}
public Arrayable[] returnSomething() {
return arrayable;
}
}
Main.java
public class Main {
public static void main(String args[]) {
Example ex1 = new Example();
Example ex2 = new Example();
Example[] ex3;
ex3[0] = ex1;
ex3[1] = ex2;
Array2D a2d = new Array2D(ex3);
Example[] finish = a2d.returnSomething();
}
}
The only problem I see with Method 2 is that for any class you want to give to Array2D, it has to extend Arrayable. Oh, and the fact that it takes double the time to do. Input??
If Method 1 is the way to go in this situation, please provide an example. I'm basically new to generic classes and setting them up. Thank you!
From what I understood, you want it to be generic for all types of objects, but when you instantiate it, it should only accept subclasses of the declared type. If this is the case, use generics. After you instantiate it, it will automatically accept subclasses of the defined type.
Basically, use your first method. Then change your main like this:
public class Main {
public static void main(String args[]) {
Arrayable[] classArray = {
new SubClass1(),
new SubClass2()
};
Array2D<Arrayable> a2d = new Array2D<>(classArray);
Arrayable[] array = a2d.returnSomething();
}
}
I wonder if my aproach into modelling difficulty level for my game is good.
public abstract class AbstractDifficulty {
public AbstractDifficulty() {
}
public abstract int enemyWaves();
public abstract int enemiesInWave();
public abstract long enemyWaveIntervalMilis();
}
And then several subclasses which implement those methods, for example.
public class EasyDifficulty extends AbstractDifficulty {
#Override
public int enemyWaves() {
return 1;
}
#Override
public int enemiesInWave() {
return 10;
}
#Override
public long enemyWaveIntervalMilis() {
return 500;
}
}
I wonder if there is a simpler way to do this, but the same easy and clean to use as this.
Edit: Could someone be so kind to explain to me why this question got minus votes. Is something wrong with this code, or my explanation ? Thanks.
Your design will do the job, but it seems what you want to have is a container class. So instead having a method for each value, have a (final) field with the value and a getter. They can be set e.g. in the constructor.
If your difficulty modes are known and few, consider having an enum, which are final and easier to use.
enum Difficulty {
EASY(1, 10, 5000),
MEDIUM(2, 15, 4000),
HARD(4, 20, 3500);
private final int enemyWaves;
private final int enemiesInWave;
private final long enemyWaveIntervalMilis;
Difficulty(int enemyWaves, int enemiesInWave, long enemyWaveIntervalMilis ){
this.enemyWaves = enemyWaves;
this.enemiesInWave = enemiesInWave;
this.enemyWaveIntervalMilis = enemyWaveIntervalMilis;
}
public int getEnemyWaves() {
return enemyWaves;
}
public int getEnemiesInWave() {
return enemiesInWave;
}
public long getEnemyWaveIntervalMilis() {
return enemyWaveIntervalMilis;
}
}
One alternative is to not have different difficulty classes, but just one difficulty class with different instances being the different difficulties (so, a class with attributes enemyWaves, enemiesInWave and enemyWaveIntervalMilis, and different instances with different settings).
Your solution looks fine. If you want to increase readability you can just remove the constructor from the abstract class, since that is created by Java as default anyway.
I also vote for an interface instead of an abstract class unless there is a specific reason to use abstract class.
I also feel that for the specific problem you do not need different classes, but rather different instances of the same class. In that case I would use the final fields set by constructor and then the methods return the values.
public class Difficulty {
final private int enemyWaves;
public Difficulty(final enemyWaves){ this.enemyWaves = enemyWaves; }
#Override
public int enemyWaves() {
return this.enemyWaves;
}
}
I would like to ask you some tips about this java scenario:
I have a simple interface called Sequence that performs some basic operation. Now I would like to implement some additional methods in a separate class, called SequenceWrapper, that implements the Sequence defined above. Here is some example code that looks like my real code:
public interface Sequence {
public void methodOne();
public int methodTwo();
}
public abstract class SequenceWrapper implements Sequence {
private wrappedSequence = null;
public SequenceWrapper(Sequence sequence){
this.wrappedSequence = sequence;
}
public void methodOne(){
wrappedSequence.methodOne();
}
public int methodTwo(){
return wrappedSequence.methodTwo();
}
}
public class ConcreteWrapper extends SequenceWrapper {
public ConcreteWrapper(Sequence sequence){
super(sequence);
}
// Just an example
public int addMethodOne(){
int a = super.methodTwo();
return a + 3;
}
}
Now if I want to implements a class with another method (say 'addMethodTwo()') I can simply extends the 'ConcreteWrapper' class and add only the new method:
public class ConcreteWrapperTwo extends ConcreteWrapper {
public ConcreteWrapperTwo(Sequence sequence){
super(sequence);
}
public int addMethodTwo(){
int a = super.methodTwo();
return a + 30;
}
}
What do you think? Is this code correct or it's preferable another strategy??
Thanks in advance
First, your private wrappedSequence = null; has no type.
I suppose you meant private Sequence wrappedSequence = null;
Second, in your example you will never be able to instantiate any of the classes, since all of them receive another Sequence in the constructor and there is no way of create the first instance of Sequence.
Third, composition over inheritance is a good approach, if you really need it. Usually you wrap an object when you need to hide or protect the access to the wrapped object. In your case, within the wrapper you are exposing all of the methods of the wrapped object. You then create new methods that will affect the wrapper object, but not the wrapped one.
What you probably need is just a normal inheritance scenario:
I would like to walk you through you a breakdown for this Java scenario:
I have a simple interface called Sequence that performs some basic operation. Now I would like to implement some additional methods in a separate class, called SequenceWrapper that implements the Sequence as defined above. Here is some example code to explain what I mean:
public interface Sequence {
public void methodOne();
public int methodTwo();
}
public abstract class AbstractSequence implements Sequence {
public SequenceWrapper( ){ }
public void methodOne(){
//basic behavior here
}
public int methodTwo(){
//basic behavior here
}
}
public class ConcreteSequence extends AbstractSequence {
public ConcreteSequence ( ){
super( );
}
// Just an example
public int addMethodOne(){
int a = methodTwo();
return a + 3;
}
}
public class ConcreteSequenceTwo extends AbstractSequence {
public ConcreteSequenceTwo( ){
super( );
}
public int addMethodTwo(){
int a = methodTwo();
return a + 30;
}
}
I have a question about putting a Java enum in the interface.
To make it clearer, please see the following code:
public interface Thing{
public enum Number{
one(1), two(2), three(3);
private int value;
private Number(int value) {
this.value = value;
}
public int getValue(){
return value;
}
}
public Number getNumber();
public void method2();
...
}
I know that an interface consists of methods with empty bodies. However, the enum I used here needs a constructor and a method to get an associated value. In this example, the proposed interface will not just consist of methods with empty bodies. Is this implementation allowed?
I am not sure if I should put the enum class inside the interface or the class that implements this interface.
If I put the enum in the class that implements this interface, then the method public Number getNumber() needs to return the type of enum, which would force me to import the enum in the interface.
It's perfectly legal to have an enum declared inside an interface. In your situation the interface is just used as a namespace for the enum and nothing more. The interface is used normally wherever you use it.
Example for the Above Things are listed below :
public interface Currency {
enum CurrencyType {
RUPEE,
DOLLAR,
POUND
}
public void setCurrencyType(Currency.CurrencyType currencyVal);
}
public class Test {
Currency.CurrencyType currencyTypeVal = null;
private void doStuff() {
setCurrencyType(Currency.CurrencyType.RUPEE);
System.out.println("displaying: " + getCurrencyType().toString());
}
public Currency.CurrencyType getCurrencyType() {
return currencyTypeVal;
}
public void setCurrencyType(Currency.CurrencyType currencyTypeValue) {
currencyTypeVal = currencyTypeValue;
}
public static void main(String[] args) {
Test test = new Test();
test.doStuff();
}
}
In short, yes, this is okay.
The interface does not contain any method bodies; instead, it contains what you refer to as "empty bodies" and more commonly known as method signatures.
It does not matter that the enum is inside the interface.
Yes, it is legal. In a "real" situation Number would implement Thing, and Thing would probably have one or more empty methods.