Answer the question
In order to leave comments, you need to log in
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
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.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question