有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将我的方法从我的子类使用到我的主类中?

我试图从我的主类hangman中的子类hangmanwords调用这些方法。代码如下:

public class hangManWords {
    //declares words
    String [] words = { "Highschool", "Government", "Continents", "Professors", "Programmer", "Dealership", "Controller", "Motorcycle", "Lightsaber"}; 

    public void randomizeWords(String [] words) {
        //randomize the words
        for (int i = words.length - 1; i > 0; i--) {
            //generate a random index
            int j = (int)(Math.random() * (i + 1));

            //swaps list i with list j
            String temp = words[i];
            words[i] = words[j];
            words[j] = temp;
        }
    }

    public  String getNextWord (String [] words) { //gets the next random word
        for (int i = 0; i < words.length; i++) {

            if (words[i] == null) {
                continue;
            }
            String temp = words[i];
            words[i] = null;
            return temp;
        }
        return null;

    }
}

以下是我的主要部分,我试图使用它:

randomizeWords(words); //randomly generates a word from the word list

//players first word
guessThisWord = getNextWord(words);
guessThisWord = hideWord(guessThisWord, originalWord);//hides the word with _

共 (3) 个答案

  1. # 1 楼答案

    The others have already mentioned how to cast objects to get an answer to your question, but asking that question in the first place points to a possible design problem. Some possible reasons:

    • The method is in the wrong place.
    • The code which calls the method is in the wrong place.
    • The subclass should not extend the other class. It's best to prefer composition over inheritance. And when inheriting, the code should follow the Liskov substitution principle.

    • The classes are non-cohesive, they have more than one responsibility, and they should be split into multiple classes.

    Call a method of subclass in Java

  2. # 2 楼答案

    在基类中声明虚拟方法,在子类中实现它们。现在,如果对象是子类类型,那么在基类中声明的方法中对这些虚拟方法的所有调用都将调用子类方法

  3. # 3 楼答案

    你是说像这样吗

    public class Hangman {
    
        public static void main(String[] argv) {
            // Instantiate the class.
            hangManWords g = new hangManWords();
    
            // Call the methods...
    
            // g has access to `words` so no need for an argument.
            g.randomizeWords(); //randomly generates a word from the word list
    
            // g has access to `words` so no need for an argument.
            //players first word
            guessThisWord = g.getNextWord();
    
            // I don't see `hideWord` and `originalWord` defined, but assume they are somwehere.
            guessThisWord = g.hideWord(guessThisWord, originalWord); //hides the word with _
        }
    }
    

    注释

    您应该考虑启动^ {CD1>}大写的名称,如^ {< CD2>}/P>