Question about the nature of legacy Java classes

So, I think I have a pretty simple question. Say there is an open source Java program called com.cow.moo that you included in your com.bee.buzz project.

moo has a bunch of cool classes, most of which you don't want to touch, but there is a couple that you make. Now at this point, it is best to extend the classes you want to change, right? (I know that a lot has been said about continuations against guns, but none of these classes is an interface, so the question is nothing.)

My question is: let's say this is a class in moo:

package com.cow.moo;
public class Milk {
    private float currentMilk;
    public int getMilk() { /* Stuff */ }
    public float convertToGallons (float liquid) { /* More Stuff */ }
}

Now, let's say I just want to use getMilk in my new class, which extends Milk. However, getMilk in Milk relies on private variables (like currentMilk) and other functions that I won't include (like convertToGallons.) Do I have to include these other variables and functions if I want my new function to work correctly? I don’t want to change the function much, just add a little to it. What is the best way to do this?

General advice on creating a larger project can also be useful. I suggest that for some Java experts, it won't even take five seconds here to answer this question. Thank you for your time.

+3
source share
5 answers

, , getMilk , Milk. getMilk Milk (, currentMilk) , (, convertToGallons.) , , ?

. , ( ) , . , (, HoneyMilk) convertToGallons get-go.

getMilk , ( ). - " " " ". , getMilk, . ( , ?!), , , . , .

+1

.

, , ,

public interface MilkProvider { public float getMilk(); }
public class Milk implements MilkProvider { // same as you example }

, :

public class MyMilk implements MilkProvider {
  private MilkProvider milk; 

  public MyMilk(int someValue) {
    milk = new Milk(someValue);  // unfortunatly we can't get rid of a depencency
                                 // to the concrete class because we need to create
                                 // something. An existing factory could help, but
                                 // but usually there none implemented.
  }

  public float getMilk() {
    float result = milk.getMilk();
    // do somethink with the result
    return float;
  }
}
+6

, ( ), ( ) .

+1

(getters seters), .

AOP (Aspect Oriented Programming), moo .

.

, .

0

, Java-, . ( , ), , ( ). AspectJ , , .

0

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


All Articles