Object-oriented programming is concerned with isolating concepts of a problem domain into separate entities and then using those entities to solve problems. Concepts related to a problem can only be considered once they've been identified. In other words, we can form abstractions from problems that make those problems easier to approach.
Once concepts related to a given problem have been identified, we can also begin to build constructs that represent them into programs. These constructs, and the individual instances that are formed from them, i.e., objects, are used in solving the problem.
A class defines the attributes of objects, i.e., the information related to them (instance variables), and their commands, i.e., their methods.
The values of instance (i.e., object) variables define the internal state of an individual object, whereas methods define the functionality it offers.
A Method is a piece of source code written inside a class that's been named and has the ability to be called. A method is always part of some class and is often used to modify the internal state of an object instantiated from a class.
An object is always instantiated by calling a method that created an object, i.e., a constructor by using the new
keyword.
A class specifies what the objects instantiated from it are like.
A class is defined to represent some meaningful entity, where a "meaningful entity" often refers to a real-world object or concept. If a computer program had to process personal information, it would perhaps be meaningful to define a separate class Person
consisting of methods and attributes related to an individual.
Variables defined inside a class are called instance variables, or object fields or object attributes.
The keyword private means that the variables are "hidden" inside the object. This is known as encapsulation.
You can also draw a class diagram to depict a class. An empty person-named class looks like this:
In the class diagram, the variables associated with the class are defined as "variableName: variableType". The minus sign before the variable name indicates that the variable is encapsulated (it has the keyword private).
We have now defined a blueprint — a class — for the person object. Each new person object has the variables name
and age
, which are able to hold object-specific values. The "state" of a person consists of the values assigned to their name and age.