110 likes | 126 Vues
Introduction to Object Oriented Programming. Unit 2. Intro to OOP. We need to learn how to speak OOP, let’s start with some basic definitions Objects - packet containing data and procedures Class - template for creating objects Methods - deliver a service
E N D
Intro to OOP We need to learn how to speak OOP, let’s start with some basic definitions • Objects - packet containing data and procedures • Class- template for creating objects • Methods- deliver a service • Attributes - entities that define the properties of an object
Intro to OOP • Instance - an object that belongs to a class • Message- request to execute a method • Inheritance - a mechanism for allowing the reuse of a class specification
Objects • Think of an object as a noun • A person, place or thing • For example a character in a video game (Link from Zelda)
Example: Hero Class Hero is much like a variable type. “link” is an instance of the class Hero Hero link; voidsetup() { link = new Hero(); } class Hero { Hero() { // Empty for now } } Create Link as a character using the keyword new. Use the key word classto create an object template. The constructor is much like setup(). It will help assign attributes to our hero
Attributes • An object can also have properties that define what the object actually is • We refer to these entities as attributes For example Link has attributes of: - health - position - image (note: in our objects we only write methods and attributes that we need)
Example: Attributes Hero link; voidsetup() { float x = random(width); link = new Hero(x); println(link.x); } class Hero { float x; Hero(float xPos) { x = xPos; } } Access Link's x position using the dot (.) convention “x” is an attribute of Hero Assign the Hero's x position attribute
Methods • An object usually has a function or can perform certain tasks • We refer to these as methods or functions For example Link can: - move() - attack() - jump()
Example: Methods Hero link; voidsetup() { size(800, 500); float x = random(width); link = new Hero(x); } voiddraw() { background(255); link.move(); } class Hero { float x; Hero(float xPos) { x = xPos; } void move() { x += 2; ellipse(x, 100, 10, 10); } } Access Link's move method using the dot (.) convention Move the Hero by changing the x attribute
Action • Convert your Bumper Car exercise using an object oriented programming style by creating a “Blob” class • Assign size(float), speed (float), position (floats or Pvector) and enemy (Blob) attributes • Create a method to move your blob slowly and randomly about the screen • Create an array of Blobs (~ 15) • Create an attack method that allows a blob to “eat” another blob, decreasing the enemy's size and increasing its own. • Create a method (not in the Blob class) that once a blob has attacked it finds another larger blob to attack.