Object-oriented programming - Laboratory 3


Schedule Next
Temat: Java 3

Third Java program

Method overloading
This
Constructor chain
Static: variable, block, method
Array
Random
All the previous things

Final code from classes

package com.company;

import java.util.Scanner;
import java.util.Random;

public class Main {

    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        Random rand = new Random();

        System.out.println(Person.getNumberOfPerson());

        Person[] persons = new Person[3];

        persons[0] = new Person("Rafal", rand.nextInt(100));
        persons[1] = new Person("Random", 44, "flu");

        System.out.println("Give me the name");
        String name = in.nextLine();
        System.out.println("Give me the age");
        int age = Integer.parseInt(in.nextLine());
        persons[2] = new Person(name, age);

        System.out.println("Number of Person in the system: "+Person.getNumberOfPerson());

        coronavirus virus = new coronavirus();
        virus.affectPerson(persons[rand.nextInt(3)]);
        System.out.println("Affected person is "+virus.whoIsAffectedName());
        virus.affectPerson(persons[rand.nextInt(3)]);
        System.out.println("Affected person is "+virus.whoIsAffectedName());
        number.coronavirus virus2 = new number.coronavirus();

        System.out.println("Number of viruses: " + coronavirus.getNumberOfViruses());
    }
}
package com.company;

public class Person
{
    private String name;
    private int age;
    private String accompanyingDisease;

    private static int numberOfPerson;
    static
    {
        numberOfPerson = 0;
    }
    public static int getNumberOfPerson()
    {
        return numberOfPerson;
    }

    public Person(String name, int age)
    {
        this.name = name;
        this.age = age;
        numberOfPerson++;
        System.out.println("You are the "+this.getNumberOfPerson()+" person in the system.");
    }

    public Person(String name, int age, String accompanyingDisease)
    {
        this(name, age);
        this.accompanyingDisease = accompanyingDisease;
    }

    public String getName() {
        return name;
    }
    public int getAge() {
        return age;
    }
}
package com.company;

public class coronavirus
{
    private Person affected;
    private static int numberOfViruses;

    coronavirus()
    {
        numberOfViruses++;
    }

    public void affectPerson(Person person)
    {
        this.affected = person;
    }

    public static int getNumberOfViruses()
    {
        return numberOfViruses;
    }

    public String whoIsAffectedName()
    {
        return affected.getName();
    }
}