简体   繁体   English

java使用抽象类

[英]java using abstract classes

Say i wanted to create a variety of shapes consisting of a line, circle, square etc For the line, i ask for 4 coordinates (x,y) (x,y); 假设我想创建由直线,圆,正方形等组成的各种形状。对于直线,我要求输入4个坐标(x,y)(x,y);

I then have a different class called point which must contain 2 fields: int x, y. 然后,我有一个名为point的不同类,该类必须包含2个字段:int x,y。 It must have a constructor to initialize its field's values and the required get methods to read those values. 它必须具有一个构造函数来初始化其字段的值,以及必须的get方法来读取这些值。

Shape which is an abstract class to be extended by all shapes. Shape是要由所有形状扩展的抽象类。 It should contain the signature of all the methods that a shape must have. 它应包含形状必须具有的所有方法的签名。 The implementation of each method may be different in each class that extends this abstract class. 在扩展此抽象类的每个类中,每个方法的实现可能有所不同。

then another class Line which is a shape (extends Shape), it should have these fields: 然后是形状的另一类Line(扩展Shape),它应该具有以下字段:

- String TYPE = "Line"
- MyPoint p1,p2 
- Constructors 
- get methods for class fields such as getP1()
- Length() : calculates the length of a line returning a double rounded to two decimal points   
- Area() : which will return a the value zero as double
- renderShape(Graphics2D g2d) : used to draw the line to the screen. This method is provided for you, no need to edit it.
- printDetails(): will print the shape details , check typical input/output

I am just wandering how you would be able to get the coordinates from the original class and print them out in the Line class, thanks :) 我只是在徘徊,您将如何从原始类中获取坐标并在Line类中将其打印出来,谢谢:)

Define an abstract class shape. 定义抽象类的形状。 In this class define an abstract method print (or something like that). 在此类中,定义一个抽象方法print(或类似的东西)。

Override this method in your Line class. 在Line类中重写此方法。 And there you print you four coordinates. 然后在此处打印四个坐标。

public abstract class Shape {
  public abstract void printCoordinates();
}

public class Line extends Shape {
   @Override
   public void printCoordinates() {
      System.out.println(.... print your coordinates here);
   }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM