Today I learned how to make classes and objects. You must
first define your class. Like I explained in earlier post, a class is a
blueprint and an object is an instant of that class. In our game an example of
a class would be body, and an object of that class would be the sun. When
defining a new class you must type class then the name of your class. After
that you must define certain aspects of your class. These aspects may include
things like mass, density, and velocity. These are called instance variables.
When declaring objects you define those specific values for
those instance variables. First you must make a new object by typing (class_name
object_name = new class_name()).
Just like when you’re making an array you must use the key word new when making an object. After you
have created your object you can then define values to your instance variables.
Extending the example above, you can make the mass = 34 and the velocity = 9.
Below is another example where I made a class called Person with instance variables
of age and name. Then I defined those variables for two objects.
class Person{
// Instance
variables (data or "state")
String
name;
int age;
// Classes can
contain
// 1. Data
// 2.
subroutines (methods)
}
public class Objectsclass {
public static void main(String[] args) {
Person
person1 = new Person();
person1.name = "Joe";
person1.age = 33;
Person
person2 = new Person();
person2.name = "Sarah";
person2.age = 67;
System.out.println(person1.age);
}
}
No comments:
Post a Comment