• Profile
  • Resume
  • Portfolio
  • Blog
Avatar

Nelson Silva

A human. Being. Coffee lover.

Blog

I Write My Thoughts Here

Classes and Objects in Java

March 15, 2022 Java

In this post, you will learn how to work with classes and objects so that you can use that same knowledge and thus evolve.

  • a class represents a set of objects, and defines their behavior through methods and which states it is able to maintain through its attributes;
  • an object is an instance of a class and is capable of storing states through its attributes and reacting to messages sent to it;
  • var is an implicit variable type and this same type is determined according to the variable content (there is a need for the variable to be initialized to use var and you cannot change its type after this same initialization).
package com.caffeinealgorithm.programminginjava;

public class Main {
  public static void main(String[] args) {
    var enemy1 = new ClassesAndObjects();
    var enemy2 = new ClassesAndObjects();

    enemy1.attack(); // I was attacked and lost a live.
    enemy1.attack(); // I was attacked and lost a live.
    enemy1.attack(); // I was attacked and lost a live.
    enemy1.checkLife(); // I am still in combat and have 2 lives.
    enemy2.checkLife(); // I am still in combat and have 5 lives.
  }
}
package com.caffeinealgorithm.programminginjava;

public class ClassesAndObjects {
  int lives = 5;

  public void attack() {
    System.out.println("I was attacked and lost a live.");
    lives -= 1;
  }

  public void checkLife() {
    if (lives <= 0)
      System.out.println("I am dead because I don't have any more lives.");
    else
      System.out.printf("I am still in combat and have %d lives.\n", lives);
  }
}

Don’t forget to watch the video and you can always read this post in Portuguese.

Happy coding!

Previous Next

Categories

  • Announcements
  • Python
  • C#
  • Java
  • Go

Latest Posts

  • for Loop in Go
    May 5, 2022
  • Switch in Go
    May 4, 2022
  • Comparison Operators in Go
    May 3, 2022
+351913416022
contact@nelsonsilvadev.com
Porto, Portugal
Nelson Silva © 2022 All Rights Reserved