简体   繁体   中英

How would I move code to a different class?

In the SimpleApp tutorial, the author puts all of his code inside one class file. Causing the rain and the bucket to be within it.

I tried just taking the code and putting it into another class but then I would have duplicate methods in my code, and logically it would be incorrect. For example, I cannot have two create methods in a game.

How would I take the rain or the bucket from the tutorial and put it into a different class?

You'd abstract out the common functions into an Abstract class or Interface and then have both rain and bucket inherit from that class.

So, for your particular example, go through both classes, find all the common functions and abstract them into a superclass.

It's very simple: you could benifit from OOP style coding:
Just use a super class RainBucket that has all the methods in it with minimal code with each method.
Extend the other two classes from this super class and override in it the methods that your class wants to use, this way you would be acomplishing the following OOP rules:

  1. Inheritence: when you derive from the super class two other objects:

    class Bucket extends RainBucket {

    class Rain extends RainBucket {

  2. polymorphism: you can declare two objects from the same super class but by assigning to the two different derived classes as values like this:

    RainBucket bucket = new Bucket() and

    RainBucket rain = new Rain()

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