Learn JAVA: INTRODUCTION TO CLASSES

Classes: Syntax

The fundamental concept of object-oriented programming is the class.
class is the set of instructions that describe how an instance can behave and what information it contains.
Java has pre-defined classes such as System, which we’ve used in logging text to our screen, but we also need to write our own classes for the custom needs of a program.
Here’s a definition of a Java class:
public class Phone { // scope of Phone class starts after curly brace public static void main(String[] args) { // scope of main() starts after curly brace // program tasks } // scope of main() ends after curly brace } // scope of Phone class ends after curly brace
This example defines a class named Phonepublic is an access level modifier that allows other classes to interact with this class. For now, all classes will be public.
This class has a main() method, which lists the tasks performed by the program. main() runs when we execute the compiled Phone.class file.

Classes: Constructors

We create objects (instances of a class) using a constructor method. The constructor is defined within the class.
Here’s the Car class with a constructor:
public class Car { public Car() { //constructor method starts after curly brace //instructions for creating a Car instance } //constructor method ends after curly brace public static void main(String[] args) { // program tasks } }
The constructor, Car(), shares a name with the class.
We create instances by calling or invoking the constructor within main(). This example assigns an instance to the variable ferrari:
public class Car { public Car() { } public static void main(String[] args) { /* invoke a constructor using 'new', the name, and parentheses: new Car() */ Car ferrari = new Car(); } }
As with other variable declarations, we specify the type: Car, and name: ferrari. Variables that reference an instance have a type of the class name.
We invoke the constructor method: Car(), and use the keyword new to indicate that we’re creating an instance. Omitting new causes an error.
This is the first time we’ve called a method that we’ve also defined. main() is run automatically and we did not define the println() method.
Introducing a second method is a big step in your programming journey, congratulations!

Classes: Instance Fields

We don’t care about memory location, but our instances have no other characteristics!
We’ll add associated data to an object by introducing instance variables, or instance fields. Instance fields are the state in our objects.
We want Car instances of different colors, so we declare a String color instance field.
public class Car { /* declare fields inside the class by specifying the type and name */ String color; public Car() { /* instance fields available in scope of constructor method */ } public static void main(String[] args) { // body of main method } }
The declaration is within the class and the instance variable will be available for assignment inside the constructor.
Fields are a type of state each instance will possess. One instance may have "red" as its color, another "blue", etc.

Classes: Constructor Parameters

We’ll use a combination of constructor method and instance field to create instances with individual state.
We need to alter the constructor method because now it needs to access data we’re assigning to the instance.
Our Car constructor now has a parameterString carColor.
public class Car { String color; // constructor method with a parameter public Car(String carColor) { // parameter value assigned to the field color = carColor; } public static void main(String[] args) { // program tasks } }
We need a value for the instance field color, so we’ve added String carColor as a parameter.
Parameters specify the type and name of data available for reference within a method’s scope.
We’ve already seen a parameter in the main() method: String[] args, but this is the first time we’re using the parameter value within a method body.
The parameter carColor references the value passed in during a method call:
new Car("blue"); // carColor references "blue" inside constructor new Car("yellow"); // carColor references "yellow" inside constructor
Within the constructor, we assign the parameter value to the instance field.
Instance fields are available for assignment inside the constructor because we declared them within the class.

Classes: Assigning Values to Instance Fields

Now that our constructor has a parameter, we must pass values into the method call. These values become the state of the instance.
Here we create an instance, ferrari, in the main() method with "red" as its color field:
public class Car { String color; public Car(String carColor) { // assign parameter value to instance field color = carColor; } public static void main(String[] args) { // parameter value supplied when calling constructor Car ferrari = new Car("red"); } }
We pass the String value "red" to our constructor method call: new Car("red");.
The type of the value given to the invocation must match the type declared by the parameter.
Inside the constructor, the parameter carColor refers to the value passed in during the invocation: "red". This value is assigned to the instance field color.
color has already been declared, so we don’t specify the type during assignment.
The object, ferrari, holds the state of color as an instance field referencing the value "red".
We access the value of this field with the dot operator (.):
/* accessing a field: objectName.fieldName */ ferrari.color; // "red"

Classes: Multiple Fields

Objects are not limited to a single instance field. We can declare as many fields as are necessary for the requirements of our program.
Let’s change Car instances so they have multiple fields.
We’ll add a boolean isRunning, that indicates the car engine is on and an int velocity, that indicates the speed at which the car is traveling.
public class Car { String color; // new fields! boolean isRunning; int velocity; // new parameters that correspond to the new fields public Car(String carColor, boolean carRunning, int milesPerHour) { color = carColor; // assign new parameters to the new fields isRunning = carRunning; velocity = milesPerHour; } public static void main(String[] args) { // new values passed into the method call Car ferrari = new Car("red", true, 27); Car BMW = new Car("blue", false, 70); System.out.println(BMW.isRunning); // false System.out.println(ferrari.velocity); // 27 } }
The constructor now has multiple parameters to receive values for the new fields. We still specify the type as well as the name for each parameter.
Ordering matters! We must pass values into the constructor invocation in the same order that they’re listed in the parameters.
// values match types, no error Car honda = new Car("green", false, 0); // values do not match types, error! Car junker = new Car(true, 42, "brown");

Quickly lets take a example for better understanding :

1.
Add two new instance fields for Store.
inventoryCount of type intinventoryPrice of type double.
2.Update the Store constructor method with the new parameters.
The parameters should be productcount, and pricein that order.
You must use that order and include the types for each parameter.
For example, product is of type String because that value is assigned to the instance field String productType.
3.In the body of the Store constructor, assign the parameter values to the appropriate instance fields.
4.Inside main(), create an instance of Store called cookieShop.
cookieShop has "cookies" as the product.
cookieShop has 12 cookies to sell and each cookie costs 3.75.
Java basics

Classes: Review

Java is an object-oriented programming language where every program has at least one class. Programs are often built from many classes and objects, which are the instances of a class.
Classes define the state and behavior of their instances. Behavior comes from methods defined in the class. State comes from instance fields declared inside the class.
Classes are modeled on the real-world things we want to represent in our program. Later we will explore how a program can be made from multiple classes. For now, our programs are a single class.
public class Dog { // instance field String breed; // constructor method public Dog(String dogBreed) { /* value of parameter dogBreed assigned to instance field breed */ breed = dogBreed; } public static void main(String[] args) { /* create instance: use 'new' operator and invoke constructor */ Dog fido = new Dog("GSD"); /* fields are accessed using: the instance name, `.` operator, and the field name. */ fido.breed; // "GSD" } }

No comments:

Powered by Blogger.