【发布时间】:2020-02-07 06:32:27
【问题描述】:
我是初学者,之前几乎没有编程经验,我希望我能学到一些东西。我认为椭圆是最好的对象。
【问题讨论】:
-
标题已缩短,给您带来的不便深表歉意。
标签: java class object processing
我是初学者,之前几乎没有编程经验,我希望我能学到一些东西。我认为椭圆是最好的对象。
【问题讨论】:
标签: java class object processing
假设我想在 Processing 中制造汽车。我可以有几个变量来描述关于汽车的信息,比如bodyColor、yearMade 或model。但是,使用全局变量来定义它们是多余的。我们在 Java 中使用 Objects(这是 Processing 的组成部分)来定义变量和方法的集合。
类是对象的蓝图。你不能有一个没有类的对象来定义它。例如,如果我们要创建一个Car 对象,我们需要定义一个Car 类型。这是使用类完成的。
class Car //defines the class Car
{
color bodyColor; //the body color of the car
int yearMade; //the year the car was made
String model; //the model of the car
void drive() {
//add code for making the car move here
}
void paint(color newColor) {
bodyColor = newColor; //paints the car to a new color
}
}
每个类都可以有变量,比如model,和方法,比如drive()。
现在请记住,这是一个蓝图,而不是一个对象。要创建Car 对象,类需要一个称为构造函数的东西。构造函数是使用类中的信息构建对象的东西。
Car内部:
public Car(color colorChosen, int thisYear, String modelName) {
bodyColor = colorChosen;
yearMade = thisYear;
model = modelName;
}
我们可以想象,当我们在代码的任何地方调用这个函数时,我们正在创建一个新的汽车对象:
Car myFirstCar = new Car(color(0, 255, 0) /*green*/, 2020, "Toyota");
在该示例中,myFirstCar 是一辆绿色汽车,2020 年制造,是一辆丰田汽车。
您还可以获取和设置对象的属性:
print(myFirstCar.yearMade); //2020
myFirstCar.model = "Honda";
print(myFirstCar.model); //Honda
myFirstCar.paint(color(255, 0, 0)); //paints the car red. Now myFirstCar.bodyColor = color(255, 0, 0).
你可以用对象做很多很棒的事情。它们对 Java 非常重要,因为它是面向对象编程的基础。随着时间的推移和实践,创建类和对象将变得轻而易举。
祝你好运。
【讨论】:
Ben Myers 已经给出的答案是对一般对象和类的一个很好的解释。
这个答案在处理中提供了一个小例子,可能有助于展示如何在处理草图中使用对象和类:
// Create two moving ellipse objects that follow the mouse pointer.
// The MovingEllipse class can be found below.
MovingEllipse movingEllipse1 = new MovingEllipse(20, 2.0);
MovingEllipse movingEllipse2 = new MovingEllipse(50, 3.2);
void setup() {
size(600, 600);
frameRate(60);
}
void draw() {
// Clear the previous frame and set the background color to anthracite.
background(56, 62, 66);
movingEllipse1.move();
movingEllipse1.draw();
movingEllipse2.move();
movingEllipse2.draw();
}
class MovingEllipse {
float x;
float y;
float speed;
float fillColor;
float ellipseWidth;
float ellipseHeight;
MovingEllipse(float position, float speed) {
this.x = position;
this.y = position;
this.speed = speed;
this.fillColor = 7 * speed * speed * speed;
this.ellipseWidth = 6.0 + speed * speed;
this.ellipseHeight = 2.0 * speed;
}
void move() {
PVector direction = new PVector(mouseX - x, mouseY - y).setMag(speed);
x += direction.x;
y += direction.y;
}
void draw() {
fill(fillColor);
ellipse(x, y, ellipseWidth, ellipseHeight);
}
}
【讨论】: