简体   繁体   中英

A class that accepts two different data types in Java?

I want to make a class that can accept two different data types for each parameter. How can this be accomplished?

I realize the code below doesn't work, but how can I make something like that work? Basically so that parameter can be an int or String or something similar?

Example:

public Combat(int attack || String attack, int defence || String defence) {
        //code to parse strings into ints

    }

It appears you want to provide an overloaded constructor . You could delegate to the int version with something like,

private int attack;
private int defence;
public Combat(int attack, int defence) {
    this.attack = attack;
    this.defence = defence;
}
public Combat(String attack, String defence) {
    this(Integer.parseInt(attack), Integer.parseInt(defence));
}

if you wanted to pass String, int or int, String as well

public Combat(int attack, String defence) {
    this(attack, Integer.parseInt(defence));
}
public Combat(String attack, int defence) {
    this(Integer.parseInt(attack), defence);
}

You should create 2 constructors. I'll put an example below:

public Test(String test){
    // blah blah blah
}
public Test(int test){
    // blah blah blah
}

So when the instance is created, it can take either parameter.

Also, don't get confused with catch statements. Catches can take multiple exceptions with one |, example:

try{
    // blah blah blah
}
catch(TestException | TestExceptionTwo e){
    // blah blah blah
}

Using a single | doesn't work with constructors or methods.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM