F
F
Fedor unknown2020-09-21 19:34:58
Java
Fedor unknown, 2020-09-21 19:34:58

How to access class fields?

Hi everybody!

there are two classes: Hero and Dragon
I need to access the fields of the Dracon class from the Hero class
to make the formula: damage = hero_power + hero_weapon - dragon_protection
how to do this?

public class Dragon {
    private int hp;        // Жизнь
    private int defence;    // защита
    private int strength;   // Сила
    private int weapon;     // оружие
    private int shield;      // щит

    public Dragon(int hp, int defence, int strength, int weapon) {
        this.hp = hp;
        this.defence = defence;
        this.strength = strength;
        this.weapon = weapon;
        this.shield = shield;
    }
}


import java.util.Scanner;

public class Hero {

    private int hp;        // Жизнь
    private int defence;    // защита
    private int strength;   // Сила
    private int weapon;     // оружие
    private int shield;      // щит



   public Hero(int hp, int defence, int strength, int weapon, int shield){
       this.hp = hp;
       this.defence = defence;
       this.strength = strength;
       this.weapon = weapon;
       this.shield = shield;
   }

    void heroAttack(){
        System.out.println("Нажмите  1 чтобы атаковать дракона!");
        Scanner sc = new Scanner(System.in);
        int user = sc.nextInt();

        if (user == 1){
            int damage = strength + weapon;
        }
    }

Answer the question

In order to leave comments, you need to log in

4 answer(s)
H
Hanneman, 2020-09-21
@Hanneman

Instead of a fish, here's a fishing rod for you: read about getters and setters in Java . It is through the getter that you will get access to the class fields. I'm sure you'll figure it out. And yes, it will be beneficial.

A
Araya, 2020-09-21
@Araya

Reflection API :D

T
Timur Pokrovsky, 2020-09-21
@Makaroshka007

Either make the variables public or create a getter

O
Orkhan, 2020-09-21
Hasanly @azerphoenix

I recommend that you read some book on Java, as well as study the principles of OOP, in particular encapsulation. You were well advised that it is better to read about getters and setters instead of giving you an answer

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question