Home  >  Article  >  Get method from class that extends another class

Get method from class that extends another class

王林
王林forward
2024-02-09 08:40:30554browse

In PHP, we often encounter situations where we need to use a method of another class in one class. At this time, we can obtain its methods by inheriting or instantiating another class. Inheritance means that one class inherits properties and methods from another class, which is achieved through the extends keyword. Instantiation refers to creating an instance object of a class and calling methods of another class through the object. Whether it is inheritance or instantiation, we can easily obtain the methods of another class in one class, improving the reusability and flexibility of the code.

Question content

I have a class that extends another class. Based on the user's input, if "a" is entered, the class needs to be subclass a, but if "b" is entered, the class will be subclass b. I have a variable that needs to be made into the main class. I can't access the subclass's methods because the variables I define are from the main class. How can I make it work?

This is an example of decomposition. The myclass variable is used elsewhere, so I need it to be available as a subclass everywhere.

public class Programm
{
   private static MainClass myClass;

   public static void main(String args[]) 
   {
      if (input == 'A') {
         myClass = new SubClassA();
         myClass.subClassAMethod(); // Can't do this becuse subClassAMethod isn't in MainClass
      } else {
         myClass = new SubClassB();
         myClass.subClassBMethod(); // Can't do this becuse subClassBMethod isn't in MainClass
      }
   }
}

I know I can put subclassamethod and subclassbmethod in the main class, but I don't want to be able to call those methods if it's not part of the subclass.

Is there a way to declare myclass to accept both subclassa and subclassb?

Solution

This means: the variable myclass exists and is restricted to point to null, or to an instance of the class such that the class is mainclass or some subtype thereof.

The way java is set up, java will simply refuse to compile any interaction with this variable unless it makes sense in all possible scenarios . p>

In other words, even if you can prove beyond a reasonable doubt that at some point in the flow of your code that variable must point to an instance of mysubclassb, the compiler won't care that.

Your coding style is questionable. This is not your java way.

Note that myclass as a variable name just screams "I don't understand how this works". This is very misleading: variables can only refer to instances, not classes.

As a side note, static is being misused in your code snippet. Static is generally not necessary for most Java projects and is a relatively advanced concept. If you don't want to know what it means, that's okay. But you must not use it. main currently has to be static (soon it won't have to be static starting with jdk22), so the solution is to get rid of static immediately.

Here is an example of how to do this. These code snippets try to make things clearer by using better names for types and variables:

class animal {}
class cat extends animal {
  void meow() {}
}
class dog extends animal {
  void howl() {}
}

class main {
  public static void main(string[] args) {
    new main().go();
  }

  void go() {
    example1('a');
  }

  private animal animal;

  void example1(char input) {
    if (input == 'a') {
      var cat = new cat();
      animal = cat;
      cat.meow();
    } else {
      var dog = new dog();
      animal = dog;
      dog.howl();
    }
  }
}

If the code new subclassa() and the code myobject.subclassamethod() are not close, then this will not work. You have to use instanceof to check if myclass (again, very bad name) is the correct type. look like:

// as part of Main.java snippet as above:
public void tryToHowl() {
  if (animal instanceof Dog dog) dog.howl();
}

This checks whether animal points to an instance of dog or an object of some subtype of type dog. If not, then if doesn't do anything as you expect (animal is not an instance of dog , so if doesn't do its contents). If it is, then create a new variable dog dog pointing to it, enter dog, so you can call dog-only methods on it.

Please note that usually using instanceof means your code is set up incorrectly. The whole point of having the variable animal animal is that it can contain any animal - if your code actually needs it to be a dog, then it should be dog dog. Alternatively, you should have a subclass of this code, a version specifically for dogs that has a field defined as dog dog. If it is a method that encodes the details of multiple objects ( if (animal instance of cat) docatthing(); else if (animal instance of dog) dodogthing(); A big list of etc. ), then it should actually be an abstract method in the animal class, and each implementation of animal provides an implementation: A file with class dog will Dog-specific code is included because that's where the dog-specific code goes.

Either way, you don't need instanceof, so if you do use instanceof, especially if beginners are doing this, then 95% of coding style wise is a very bad way to do it. "Bad" means: difficult to understand, inflexible (future changes in code requirements are something all non-academic projects always go through, requiring more effort than you think), difficult to integrate into existing libraries, often not class-specific java, that is - is not what most java programmers on the planet do, thus unnecessarily complicating the learning and understanding curve of this code.

The above is the detailed content of Get method from class that extends another class. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete