有人可以给我提供使用处理的任何类和对象的示例吗?

问题描述 投票:0回答:1

我是一个初学者,以前几乎没有编程经验,我希望可以学到一些东西。我认为椭圆形将是最好的对象。

class object processing
1个回答
0
投票

假设我想在Processing中制造汽车。我可以使用几个变量来描述有关汽车的信息,例如bodyColoryearMademodel。但是,使用全局变量来定义这些变量是多余的。我们使用Java中的Objects(这是处理的结果)来定义变量和方法的集合。

A class是对象的blueprint。没有类就不能定义对象,就不可能有一个对象。例如,如果要创建Car对象,则需要定义Car类型。使用classes

完成
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对象,该类需要一个称为constructor function。的东西。构造函数是使用该类的信息来构建对象的东西。

Car内部:

public Car(color colorChosen, int thisYear, String modelName) {
  bodyColor = colorChosen;
  yearMade = thisYear;
  model = modelName;
}

我们可以想象,当我们在代码中的任何地方调用此函数时,我们都在创建一个新的car对象:

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非常重要,因为它是面向对象编程的foundation。随着时间和实践的发展,创建类和对象将是小菜一碟。

祝你好运。

© www.soinside.com 2019 - 2024. All rights reserved.