Classe e oggetti Java (con esempio)

In questo tutorial imparerai il concetto di classi e oggetti in Java con l'aiuto di esempi.

Java è un linguaggio di programmazione orientato agli oggetti. Il concetto centrale dell'approccio orientato agli oggetti è quello di suddividere problemi complessi in oggetti più piccoli.

Un oggetto è qualsiasi entità che abbia uno stato e un comportamento . Ad esempio, una bicicletta è un oggetto. Esso ha

  • Stati : minimo, prima marcia, ecc
  • Comportamenti : frenata, accelerazione, ecc.

Prima di conoscere gli oggetti, dobbiamo prima conoscere le classi in Java.

Classe Java

Una classe è un modello per l'oggetto. Prima di creare un oggetto, dobbiamo prima definire la classe.

Possiamo pensare alla classe come a uno schizzo (prototipo) di una casa. Contiene tutti i dettagli sui pavimenti, porte, finestre, ecc. Sulla base di queste descrizioni costruiamo la casa. La casa è l'oggetto.

Poiché molte case possono essere create dalla stessa descrizione, possiamo creare molti oggetti da una classe.

Crea una classe in Java

Possiamo creare una classe in Java usando la parola chiave class. Per esempio,

 class ClassName ( // fields // methods )

Qui, campi (variabili) e metodi rappresentano rispettivamente lo stato e il comportamento dell'oggetto.

  • i campi vengono utilizzati per memorizzare i dati
  • i metodi vengono utilizzati per eseguire alcune operazioni

Per il nostro oggetto Bicycle, possiamo creare la classe come

 class Bicycle ( // state or field private int gear = 5; // behavior or method public void braking() ( System.out.println("Working of Braking"); ) )

Nell'esempio precedente, abbiamo creato una classe denominata Bicycle. Contiene un campo denominato gear e un metodo denominato braking ().

Qui, Bicycle è un prototipo. Ora possiamo creare un numero qualsiasi di biciclette utilizzando il prototipo. E tutte le biciclette condivideranno i campi e i metodi del prototipo.

Nota : abbiamo utilizzato le parole chiave privatee public. Questi sono noti come modificatori di accesso. Per saperne di più, visita i modificatori di accesso Java.

Oggetti Java

Un oggetto è chiamato istanza di una classe. Ad esempio, supponiamo che Bicycle sia una classe, quindi MountainBicycle, SportsBicycle, TouringBicycle, ecc. Possono essere considerati come oggetti della classe.

Creazione di un oggetto in Java

Ecco come possiamo creare un oggetto di una classe.

 className object = new className(); // for Bicycle class Bicycle sportsBicycle = new Bicycle(); Bicycle touringBicycle = new Bicycle();

Abbiamo utilizzato la newparola chiave insieme al costruttore della classe per creare un oggetto. I costruttori sono simili ai metodi e hanno lo stesso nome della classe. Ad esempio, Bicycle()è il costruttore della classe Bicycle. Per saperne di più, visita Java Constructors.

Qui, sportsBicycle e touringBicycle sono i nomi degli oggetti. Possiamo usarli per accedere ai campi e ai metodi della classe.

Come puoi vedere, abbiamo creato due oggetti della classe. Possiamo creare più oggetti di una singola classe in Java.

Nota : i campi e i metodi di una classe sono anche chiamati membri della classe.

Accesso ai membri di una classe

Possiamo usare il nome degli oggetti insieme .all'operatore per accedere ai membri di una classe. Per esempio,

 class Bicycle ( // field of class int gear = 5; // method of class void braking() (… ) ) // create object Bicycle sportsBicycle = new Bicycle(); // access field and method sportsBicycle.gear; sportsBicycle.braking();

In the above example, we have created a class named Bicycle. It includes a field named gear and a method named braking(). Notice the statement,

 Bicycle sportsBicycle = new Bicycle();

Here, we have created an object of Bicycle named sportsBicycle. We then use the object to access the field and method of the class.

  • sportsBicycle.gear - access the field gear
  • sportsBicycle.braking() - access the method braking()

We have mentioned the word method quite a few times. You will learn about Java methods in detail in the next chapter.

Now that we understand what is class and object. Let's see a fully working example.

Example: Java Class and Objects

 class Lamp ( // stores the value for light // true if light is on // false if light is off boolean isOn; // method to turn on the light void turnOn() ( isOn = true; System.out.println("Light on? " + isOn); ) // method to turnoff the light void turnOff() ( isOn = false; System.out.println("Light on? " + isOn); ) ) class Main ( public static void main(String() args) ( // create objects led and halogen Lamp led = new Lamp(); Lamp halogen = new Lamp(); // turn on the light by // calling method turnOn() led.turnOn(); // turn off the light by // calling method turnOff() halogen.turnOff(); ) )

Output:

 Light on? true Light on? false

In the above program, we have created a class named Lamp. It contains a variable: isOn and two methods: turnOn() and turnOff().

Inside the Main class, we have created two objects: led and halogen of the Lamp class. We then used the objects to call the methods of the class.

  • led.turnOn() - It sets the isOn variable to true and prints the output.
  • halogen.turnOff() - It sets the isOn variable to false and prints the output.

The variable isOn defined inside the class is also called an instance variable. It is because when we create an object of the class, it is called an instance of the class. And, each instance will have its own copy of the variable.

That is, led and halogen objects will have their own copy of the isOn variable.

Example: Create objects inside the same class

Nota che nell'esempio precedente, abbiamo creato oggetti all'interno di un'altra classe e abbiamo avuto accesso ai membri da quella classe.

Tuttavia, possiamo anche creare oggetti all'interno della stessa classe.

 class Lamp ( // stores the value for light // true if light is on // false if light is off boolean isOn; // method to turn on the light void turnOn() ( isOn = true; System.out.println("Light on? " + isOn); ) public static void main(String() args) ( // create an object of Lamp Lamp led = new Lamp(); // access method using object led.turnOn(); ) )

Produzione

Accendi? vero

Qui stiamo creando l'oggetto all'interno del main()metodo della stessa classe.

Articoli interessanti...