Understanding of classes

I am new to programming and ask some questions about classes.

I use Karel as an example:

public class Karel extends robot{
   ....

}

then I expand Karel:

public class SuperKarel extends Karel{
   ....

}

but then I want to organize several groups of methods:

public class KarelJumps extends SuperKarel {
    ....

}

public class KarelColor extends SuperKarel {
    ....

}

But if I want to make a Karel jump, I need to instantiate it KarelJumpssooner SuperKarel. But since there KarelJumpsis another object, then KarelColorI could not use any of its methods.

I would just put all the methods KarelJumpsand KarelColor inside SuperKarel?I just make one big object?

+3
source share
6 answers

, , , . , , . , .

, , . "Code Complete" . , , , .

+4

, , .

" ".

. wiki:

S T, T S - .

, , , , , .

+2

, Karel KarelColor, .

KarelJumps KarelColor . , :

public class SuperKarel extends Karel
public class KarelJumps extends SuperKarel
public class KarelColor extends KarelJumps

: , , ChrisB. , , , .

+1

, . - , . , , . Karel , , - SuperKarel, , , .

public class Karel extends robot{
    public void jump(){
    ...
    } 

   public void setColor(Color c) {
   ...
   }

}

public class SuperKarel extends Karel{
    public void jump(){
       //jump in a super way    
    } 

   public void setColor(Color c) {
       //set some super color 
   }
}
+1

, , : " ?" .

, .

Here is myK he is a Karel

oh, I wonder what he can do ... hmmm looks like a Karel can jump

myK.jump(howHigh)

hey he jumped

wonder what else he can do ...

, , - myK, mySuperK, myColouredK . Karel.

, "Karel", , Karel (, , ..), , Karel.

0

:

  • ( ).

  • . KarelJumps KarelColor , " ". () , . : ( → ).

  • Java "mixins", , : Mixins - , . , , , ( , , ).

  • You can use a delegate. The delegate then implements this method. In two Karel classes, you add a field delegateand invoke the delegate implementation:

    interface IDelegate { void method (); }
    class Delegate implements IDelegate {
        void method () { ... }
    }
    
    public class KarelJumps extends SuperKarel implements IDelegate {
        IDelegate delegate = new Delegate ();
    
        // Instead of copying the code, delegate the work
        void method () { delegate.method (); }
    }
    
0
source

Source: https://habr.com/ru/post/1713146/


All Articles