Difference Between a Class and an Object
One of the things when I began Object-Oriented-Programming that I had difficulty understanding was the
difference between a class and an object. So many developers use the words object and class interchangeably but they are different. I'm hoping that this post will help people understand the difference. A class is what defines an object. People often say that an object is an instance of an class and that is true but I want to simplify it for people who are just starting to code in an Object-Oriented-Programming Language. The way that I can explain it in the simplest terms is you must code a class in order to create an object. Let's look at the example below. I have coded a very basic class called Person which has their first name, last name, and age.
This is how you create a class
This is how you create an instance of a class a.k.a an Object
And there you have it, I have created a new person called tylor that has the first name Tylor, last name Cornett, and age 26. The class that is made of is Person but the object itself is named tylor.
This is how you create a class
public class Person
{
private String firstName;
private String lastName;
private int age;
public Person(String firstName, String lastName, int age)
{
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
public String getFirstName()
{
return firstName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getLastName()
{
return lastName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
}
This is how you create an instance of a class a.k.a an Object
Person tylor = new Person("Tylor", "Cornett", 26);
And there you have it, I have created a new person called tylor that has the first name Tylor, last name Cornett, and age 26. The class that is made of is Person but the object itself is named tylor.
Comments
Post a Comment