我如何将继承应用于非常相似的 类,例如 BlueScrollBar 和 RedScrollBar?

How would i apply inheritance to very similar classes, like BlueScrollBar and RedScrollBar?

我是编程继承的初学者,我正在尝试使用继承设计在这里设计一个 RGB 混色器,它有 3 个 classes,RedScrollBar、GreenScrollBar 和 BlueScrollBar。我首先尝试创建一个父 class,称为 ScrollBar 并尝试将其扩展到 3 classes。但是后来我意识到对于每个 class,我也需要更改它们的变量名,例如:

class BlueScrollBar {
  //establish line x1 y1 and x2 y2
  float blueLX1;
  float blueLY1;
  float blueLX2;
  float blueLY2;

  //establish the box, x, y, width and height;
  float blueBX;
  float blueBY;
  float bW = 20;
  float bH = 20;

  boolean blueMouseOver = false;
  boolean blueBoxLocked = false;

  float blueYOffset = 0.0;

  BlueScrollBar(int lx1, int ly1, int lx2, int ly2) {
    blueLX1 = lx1;
    blueLY1 = ly1;
    blueLX2 = lx2;
    blueLY2 = ly2;

    blueBX = lx1;    
    blueBY = ly2/2;
    }

   void draw(){
    if(mouseX >=blueBX-bW/2 && mouseX <=blueBX+bW/2 && mouseY >=blueBY-bH/2  && mouseY <=blueBY+bH/2 ){
      fill(0);
      blueMouseOver = true;
    } else {
      fill(255);
      blueMouseOver = false;
    }

    line(blueLX1, blueLY1, blueLX2, blueLY2);
    rect(blueBX, blueBY, bW, bH);

    if (blueBY <= blueLY1 || blueBY >= blueLY2) {
      blueBoxLocked = false;
    }

  }

  void mousePressed(){
    if(blueMouseOver){
      blueBoxLocked = true;
      blueBY = mouseY - blueYOffset;
    } else {
      blueBoxLocked = false;
    }
  }

  void mouseDragged(){
    if(blueBoxLocked){
      blueBY = mouseY - blueYOffset;
    }
  }

  void mouseReleased(){
    blueBoxLocked = false;
  }
}

对于 RedScrollBar 或 GreenScrollBar,我可以直接复制粘贴相同的代码来创建一个新的 class 但我需要将所有包含单词 'blue' 的变量更改为 'red' 或 'green' 才能正常工作。什么是更好的方法?任何帮助将不胜感激。

您的起点是正确的!创建一个名为 class 的 Scrollbar 并在 class 的构造函数中设置颜色(如果您只想 select 来自特定颜色集,则通过枚举)。这样你就有了一个 class 来解决你的问题。

我假设你知道如何制作构造函数,但如果你不评论这个答案,我会告诉你。

编辑 1:

好的,所以当你在java中创建一个class时,如果您没有明确定义一个。每当您调用 MyClass test = new MyClass();您可能只是在使用自动生成的构造函数(无需向其传递参数。)

但是,您将需要自己的自定义构造函数,因此您可以执行类似的操作。

public class ScrollBar{
    Color color;
    //your constructor.
    public ScrollBar(Color c){
        this.color = c;
    }
}

话虽这么说,但我不确定您是如何实现颜色的,或者您正在使用什么框架,所以请对上面的代码持保留态度。

请注意,如果您创建自己的构造函数,则不会为您生成默认构造函数。所以这会给你一个错误:

ScrollBar test = new ScrollBar(); // :( error
ScrollBar test = new ScrollBar(RED); // :) good

编辑 2:

很抱歉以这种方式误导您。我试图让我的代码在上面非常通用,因为我不确定你是如何处理程序中的颜色的。但是,您尝试实施 red/blue/green 将使用此方法。如果你真的只想要你列出的三种颜色,你可以将一个整数传递给你的构造函数,其中 0,1,2 对应于你想要使用的特定颜色。

即)

public class ScrollBar{

    int c = 0; //default to red if the user gives a bad value

    public ScrollBar(int c){
        if(c >=0 && c <=2){ //check bounds
            this.color = c;
        }
    }

    public setColor(){
        if(this.color == 0){
            //do something with red
        }
        else if(this.color == 1){
            //do something with blue
        }
        else{
            //do something with green
        }
    }
}