• Profile
  • Resume
  • Portfolio
  • Blog
Avatar

Nelson Silva

A human. Being. Coffee lover.

Blog

I Write My Thoughts Here

Constructors in Java

March 16, 2022 Java

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

  • the constructors have as function to initialize everything that is necessary when creating a certain object;
  • you can create several constructors in a class.
package com.caffeinealgorithm.programminginjava;

public class Main {
  public static void main(String[] args) {
    var person1 = new Constructors("Nelson", "Silva", 25);
    var person2 = new Constructors("Larissa", "Fernandes", 17);

    person1.information();
    person1.checkEntrance();

    /*
      Name: Nelson Silva
      Age: 25
      This person can enter the site because he is over 18 years old.
    */

    person2.information();
    person2.checkEntrance();

    /*
      Name: Larissa Fernandes
      Age: 17
      This person cannot enter the site because he is under 18 years of age.
    */
  }
}
package com.caffeinealgorithm.programminginjava;

public class Constructors {
  String firstName = null, lastName = null;
  int age = 0;

  public Constructors(String firstName, String lastName, int age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  public void information() {
    System.out.printf("Name: %s %s\n", firstName, lastName);
    System.out.printf("Age: %d\n", age);
  }

  public void checkEntrance() {
    if (age >= 18)
      System.out.println("This person can enter the site because he is over 18 years old.");
    else
      System.out.println("This person cannot enter the site because he is under 18 years of age.");
  }
}

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