Can this be called an Encapsulation? - java

I am new in encapsulation.
I coded a simple java program that can identify if it is given an odd or even number and I tried to use encapsulation with it. I know that encapsulation uses get and set method, but I made it this way.
Is it still considered as encapsulation?
Main
import java.util.Scanner;
public class Implement
{
public static void main(String[]args)
{
Scanner inp = new Scanner(System.in);
System.out.println("Please enter number: ");
int ent = inp.nextInt();
Practice pract = new Practice();
pract.oddeven(ent);
}
}
Practice class
public class Practice
{
public void oddeven(int a)
{
do
{
if(a>=2)
{
a-=2;
}
}
while(a>1);
if(a==1)
{
System.out.println("This number is Odd.");
}
else if(a==0)
{
System.out.println("This number is Even.");
}
}
}

Is it still considered as encapsulation?
Your class has no internal state, so there is no internal state to hide. This means that "encapsulation" (which is all about hiding internal state) is entirely moot.
I should also point out that:
Your oddeven method is buggy. It won't print anything for numbers less then zero.
That is a horribly inefficient approach to testing for odd or even.
A method that performs a calculation and prints a result to standard output is less useful, flexible and reusable than a method that does the same calculation and returns it.
There are a number of Java style violations in your code:
You are violating the rules for Java identifiers. The method name oddeven should be oddEven because "oddeven" isn't an English word.
Your indentation is all messed up.
Your use of white-space between tokens is wrong.

Encapsulation applies at object level and is specific to Method's and fields. You just have a method which acts upon an input parameter and has nothing to do with encapsulation.
Oracle's definition to data encapsulation is : "Hiding internal state and requiring all interaction to be performed through an object's methods is known as data encapsulation — a fundamental principle of object-oriented programming."

For it to be Encapsulated in the method you have to hide whats happening. Thats the true essence of Encapsulation concept. This is done by using two methods:
Getter : gets the value for the main class
Setter : set the value inside the Encapsulation class (Here private variables are used).
The following code will show a modification of yours using encapsulation:
public class implement
{
public static void main(String[]args)
{
Practice pract = new Practice();
Scanner inp = new Scanner(System.in);
System.out.println("Please enter number: ");
int ent = inp.nextInt();
pract.setNum(ent);
if(pract.getNum() == 1){
System.out.println("This number is Odd");
}else if (pract.getNum() == 0){
System.out.println("This is Even");
}
}
}
practise class:
public class Practice
{
private int x;
public int getNum(){
return x;
}
public void setNum(int a){
x = a;
do{if(x >= 2)
x -=2;
}while(x>1);
}
}

Related

How to compare two objects with random constructors

I made these 2 objects:
Fighter Lucas = new Fighter(Statistics.punchStrength,
Statistics.movementSpeed, Statistics.reflex);
Opponent Simon = new Opponent(Statistics.punchStrength2,
Statistics.movementSpeed2, Statistics.reflex2);
I want to make them "fight" by comparing their random variables, but I have no idea how to do this.
Make one class fighter and then 2 instances Fighter and Opponent ... I don't understand why you make 2 classes which are doing same job.
You Fighter class should have a method attack(Opponent)
class Figher{
// ..
public void attack(Opponent opponent){
int opponentMaxDamage = calculateHitpointsBy(opponent);
int damageByOpponent = opponent.defend(this, opponentMaxDamage);
this.lifePoints-=damageByOpponent;
}
public boolean isAlive(){
return 0< this.lifePoints;
}
// ..
}
and your Opponent class should have a method defend(Fighter)
class Opponent{
// ..
public void defend(Figher fighter, int maxAttackDamage){
int myDamage = reduceDamage(fighter,int maxAttackDamage);
int attackerDamage = calculateAttackerDamage(fighter);
this.lifePoints-=myDamage ;
}
public boolean isAlive(){
return 0< this.lifePoints;
}
// ..
}
This gives you the possibility to add more complex calculations for the life points later. Eg.: the actual damage an attacker can do to the opponent may depend on the equipment she wears. The same may be true for the damage the opponent receives.
The method isAlive() could be extracted to a common base class...
You use it this way:
Fighter Lucas = new Fighter(Statistics.punchStrength, Statistics.movementSpeed, Statistics.reflex);
Opponent Simon = new Opponent(Statistics.punchStrength2, Statistics.movementSpeed2, Statistics.reflex2);
// fight
while(Lucas.isAlive()&&Simon.isAlive())
Lucas.attack(Simon);
// report winner
if(Lucas.isAlive())
System.out.println("winner is Lucas");
if(Simon.isAlive())
System.out.println("winner is Simon");
Use getter and setter methods in both of the classes i.e Fighter and Opponent
Then
Your Fighter class looks like this
class Fighter{
private int punchStrength, movementSpeed, reflex;
public int getPunchStrength() {
return punchStrength;
}
public void setPunchStrength(int punchStrength) {
this.punchStrength = punchStrength;
}
public int getMovementSpeed() {
return movementSpeed;
}
public void setMovementSpeed(int movementSpeed) {
this.movementSpeed = movementSpeed;
}
public int getReflex() {
return reflex;
}
public void setReflex(int reflex) {
this.reflex = reflex;
}
public Fighter(int punchStrength, int movementSpeed, int reflex) {
this.punchStrength = punchStrength;
this.movementSpeed = movementSpeed;
this.reflex = reflex;
}
}
Your Opponent class look like this
class Opponent{
private int punchStrength, movementSpeed, reflex;
public int getPunchStrength() {
return punchStrength;
}
public void setPunchStrength(int punchStrength) {
this.punchStrength = punchStrength;
}
public int getMovementSpeed() {
return movementSpeed;
}
public void setMovementSpeed(int movementSpeed) {
this.movementSpeed = movementSpeed;
}
public int getReflex() {
return reflex;
}
public void setReflex(int reflex) {
this.reflex = reflex;
}
public Opponent(int punchStrength, int movementSpeed, int reflex) {
this.punchStrength = punchStrength;
this.movementSpeed = movementSpeed;
this.reflex = reflex;
}
}
Now in your main class :
Fighter Lucas = new Fighter (Statistics.punchStrength,
Statistics.movementSpeed, Statistics.reflex);
Opponent Simon = new Opponent (Statistics.punchStrength2,
Statistics.movementSpeed2, Statistics.reflex2);
int avgFighter = ((Lucas.getpunchStrength())+(Lucas.getmovementSpeed())+(Lucas.getreflex()))/3;
int avgOpponent = ((Opponent .getpunchStrength())+(Opponent .getmovementSpeed())+(Opponent .getreflex()))/3;
if(avgFighter > avgOpponent )
System.out.println("Fighter wins");
else if(avgFighter == avgOpponent)
System.out.println("Draw");
else
System.out.println("Fighter looses");
Short version
Make one class - Fighter - which has fight(Fighter otherFighter) method. In that method, resolve the fight, so that the fight() logic and Fighter implementation does not leak outside the class. For an example, see below.
Long version
What I would do is abandon idea of having Opponent and Fighter classes if they're doing the same thing and have the same fields. Instead, why not have one Fighter class? The way I understand, the only difference between your objects is that they have different values - and that does not necessarily mean that you need to belong to different classes. Hence, unless Fighter can fight some other entities that have vastly different properties, one class should be enough. Besides, you can always extend the class if you need more fields or/and methods that behave slightly differently.
Now, determining who would win the fight is a rather interesting problem because you can do it in many ways, some more maintainable than others. On the one hand, you could calculate the outcome outside the classes. However, I do not think that this is the best approach. First of all, this means you need to know quite a lot about the Fighter, and how the fights work. Imagine if someone else worked with your code and wanted to resolve a fight. Would he/she be able to do it easily, or would he/she have to consult with you?
In my opinion, the logic should not leak to the outside, as this will make your code harder to maintain in the long run. E.g., what if attributes change? What if you want to resolve fights in multiple places of your code? Are you going to create a class whose sole purpose is to resolve a fight? Seems a bit strange. Or, worse yet, are you going to copy-paste the code? If so, what will you do if you need to change the logic of an outcome? Are you sure you can adjust all code you've copy-pasted? These are the questions you should be actively thinking about.
What I immediately think when I see a class named Fighter is that the entity represented, well, fights. Wouldn't it be nice if it could resolve the fights itself? Wouldn't it be logical place to put the code? Hence, my solution would be something like this:
public class Fighter {
private int speed;
private int reflex;
private int strength;
public Fighter(int speed, int reflex, int strength) {
this.speed = speed;
this.reflex = reflex;
this.strength = strength;
}
public String fight(Fighter otherFighter) {
int thisSum = speed + reflex + strength;
int thatSum = otherFighter.speed + otherFighter.reflex + otherFighter.strength;
int outcome = thisSum - thatSum;
if (outcome == 0) {
return "Draw";
} else if (outcome > 0) {
return "First fighter won";
} else {
return "Second fighter won";
}
}
}
Notice the fight() method. You pass another Fighter instance into it and without any effort the fight is resolved. The only caveat is that you need a way to figure out to determine which attributes are 'higher' and calculate the overall outcome. There are many ways to do it, of course. I used ints for clarity and ease of use. But you could use anything you like, or implement any logic you want. In any case, now you can resolve the fight with one method call. Hence, the whole code outside the class looks something like this:
public class Main {
public static void main(String[] args) {
Fighter fighter = new Fighter(1, 2, 3);
Fighter opponent = new Fighter(4, 2, 1);
System.out.println(fighter.fight(opponent));
}
}
Naturally, fight() could be extended to contain much more complex logic. Or it could be changed to accept some common base class of opponents, monsters, or fighters, which would allow you not only to fight Fighter's, but also other entities, too. Nevertheless, one thing I would try to achieve is to have as little logic about the fight as possible outside the Fighter class, so as to not have to change code in multiple places if I change my mind about how the fights work.
By the way, I have not used getters and setters, but it would probably be a good idea if getting an attribute involves some kind of logic.

Java return multiple strings in one method

I am attempting to write a program which asks users what their pet name is, species, finds out thirst level and gives a response accordingly.
I would appreciate if someone could help me with a problem im having, in each of the 2 methods askpetname and thirstlevel there are 2 strings i want accessible throughout the entire class without using global variables.
Can someone tell me what it is i am doing incorrectly or point me in the right direction.
Also, i understand that my excess use of methods for tedious tasks is bad practice but it helps with memorising syntax.
Thanks.
class dinoo
{
public static void main(String[] p)
{
explain();
output();
System.exit(0);
}
public static void explain()
{
print("The following program demonstrates use of user input by asking for pet name.");
return;
}
public static String askpetname()
{
Scanner scanner = new Scanner(System.in);
print("Name your dinosaur pet!");
String petname = scanner.nextLine();
print("Awesome, cool dinosaur name, what species is " + petname+ " ?");
String petspecies = scanner.nextLine();
return petname, petspecies;
}
public static int thirstlevel()
{
Random ran = new Random();
int thirst = ran.nextInt(11);
int hunger = ran.nextInt(11);
return thirst,hunger;
}
public static String anger(int thirst, int hunger)
{
double angerscore = (thirst+hunger)/2;
String temper;
if(angerscore<=2)
{
temper = "Serene";
}
else if(3<=angerscore<=6)
{
temper= "Grouchy";
}
else if(6<angerscore)
{
temper = "DANGEROUS";
}
return temper;
}
public static String warning()
{
if (temper.equals("Serene"))
{
print("He's looking happy!");
}
else if(temper.equals("Grouchy"))
{
print("Ahhh hes a bit "+temper+", you better start feeding him before he gets mad!");
}
else if(temper.equals("DANGEROUS"))
{
print("GET OUT OF THERE, HES " + temper+"!!!. He will have to be put down for everyones safety.");
}
}
public static void output()
{
print(askpetname() + "'s, thirst level is "+thirstlevel()+"/10");
return;
}
public static String print(String message)
{
System.out.println(message);
return message;
}
}
That code won't compile since you can't have:
return string1, string2;
or
else if(3<=angerscore<=6)
Instead of trying to return multiple Strings, your best bet is to create a class, say called Pet, one that holds String fields for the pet's name, a Species field for its species, as well as any other fields for hunger, thirst ... that would best encapsulate all the data that makes up one logical "pet" as well as a methods such as getAnger() that returns a value for anger depending on the Pet's state. Then you can create and return a viable Pet object from your creational method.
Also, your code has lots of compilation errors, suggesting that you could improve the way that you create your code. Never try to add new code to "bad" code, to code that won't compile. If possible, use an IDE such as NetBeans, Eclipse, or IntelliJ to help you create your programs. The IDE's will flag you if any of your code contains compilation errors, and then the key is: don't add new code until you've first fixed the existing compilation error. If you can't use an IDE, then you must compile early and often, and do the same thing -- fix all errors before adding new.
First, I would recommend shooting through a tutorial first before attempting this, do all the hello worlds covering scope, objects, arrays and functions. Get familiar with Object Oriented Style, although thats not even procedural programming ... nothing returns 2 objects ... always 1 (it could be an array containing many objects, but an array is a single object)
Moving on,although this is terrible coding practice, but its ok for a beginner,since your functions are all static, create a private static variable inside each function and create getter functions
//convert
String petname = scanner.nextLine();
// To this
private static String petname = scanner.nextLine();
// Then add this below it
public static String getPetName()
{
return petname;
}
and same for every piece of data you need.
Now remove the return statement from all of your functions and declare return type as void
Then call all functions from Main,
askpetname();
thirstlevel();
then print final output (after you have called the functions) as such
System.out.println("Petname: " + getPetname + " ThirstLevel: " + getThirstLevel() + " HungerLevel: " + getHungerLevel);

Java Passing variables, avoiding toString hash

I know this has been asked before, but not in a way I understood, because I am dumb.
So.
I need to take some variables into a class, compare them against something, and then return the higher of the two. In the long run, I need to compare against a running total, but for my problem, I think the issue is considerably more fundamental. I'm not understanding how to pass a variable BACK to my main class.
import java.io.*;
public class testing123 {
public static void main(String[] args) {
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer a;
Integer b;
Integer numbersCombined;
try {
System.out.println("Please enter a number");
a = Integer.parseInt(reader.readLine());
System.out.println("Please enter a number");
b = Integer.parseInt(reader.readLine());
numbersCombined = (a + b);
testClass Check = new testClass();
System.out.println("Your numbers combined is " +numbersCombined);
System.out.println(Check);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
class testClass {
public static Integer testClass (Integer numbersCombined) {
if (numbersCombined > 100) {
numbersCombined = numbersCombined;
}
else {
numbersCombined = 100;
}
System.out.println(numbersCombined);
return numbersCombined;
}
}
If I remove the return, this will print the numbersCombined, but that's all it does. With the return in place, it doesn't execute the print line above the return, and first prints the original numbersCombined (which it shouldn't if you use, say, 10 and 20, since that's less than 100), and then prints testClass#76046e53 rather than the actual value. I know there's a way to override it, but the answers I've found don't work for me.
I know this answer: http://www.google.com/url?q=http%3A%2F%2Fstackoverflow.com%2Fquestions%2F29140402%2Fhow-do-i-print-my-java-object-without-getting-sometype2f92e0f4&sa=D&sntz=1&usg=AFQjCNGIzxlBSH8xIS7hurKe6_Euc7B8RQ
is the basic problem I'm encountering, but the overrides listed aren't really working for me, and I want integer anyway, rather than string.
In the end, what I'm "really" doing is taking a series of 4 numbers from a user, then using this function to compare whether THIS series of numbers is higher than the previous maximum, and if it is, that's the new maximum moving forward, with a loop until the user is done entering serieses of 4 numbers, and then finally printing the maximum.
I was able to write this without ANY functions, all inline, easy as pie. But once I send the comparison to a function, I don't understand how to send it back, and I've spent all day trying to understand the concept. ALL DAY. So, while I know it's going to be a stupid answer, that's because I'm stupid, but not because I didn't try (sorry, kind of defensive. Frustrated).
Fundamentally, I want to send two (this example is just one) variables to a class, compare them, change ONE of them, and return it to the main class. In this example, I'm just trying to send ONE variable, compare it, and the send it back.
You need to call the method within TestClass. Your code is already returning an integer from that method.
Once you instantiate the class run testClass.testClass(numbers)
The way you're throwing around pseudo-global variables between classes is probably the problem. Pass them through the calls like above, rather than implicitly.
Try to do something like this:
import java.io.*;
public class HelloWorld{
public static void main(String []args){
InputStreamReader input = new InputStreamReader(System.in);
BufferedReader reader = new BufferedReader(input);
Integer a;
Integer b;
Integer numbersCombined;
try {
System.out.println("Please enter a number");
a = Integer.parseInt(reader.readLine());
System.out.println("Please enter a number");
b = Integer.parseInt(reader.readLine());
numbersCombined = (a + b);
testClass Check = new testClass(numbersCombined); // constructor should be like this
System.out.println("Your numbers combined is " + numbersCombined);
System.out.println(Check);
} catch (IOException e){
System.out.println("Error reading from user");
}
}
}
class testClass {
Integer numbersCombined;
// This is a constructor
public testClass (Integer numbersCombined) {
if (numbersCombined > 100) {
this.numbersCombined = numbersCombined; // use this to represent the object
} else {
this.numbersCombined = 100;
}
System.out.println(numbersCombined);
}
// Add method toString()
public String toString() {
return this.numbersCombined.toString();
}
}

Program not working?

The question is to find the number of days between two dates.example-input-26/3/2000 and 12/8/2014.the output will be the no of days in between these two dates.
There is an error saying "identifier expected" and i=1 is highlighted.Also I am not sure whether the program is completely correct.
import java.util.*;
class yearst
{
int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30};
int i,s,s1,s2,s3,k,diy,m,m1,m2,d1,d2,y1,y2,y;
i=1;s1=0;s2=0;s3=0;diy=365;
void leap(int y)
{
if(y%4==0 && y%100!=0 || y%400==0) //for leap year
{
a[2]=29;
diy=366;
}
else
{
a[2]=28;
diy=365;
}
}
public static void main(String args[])
{
Scanner ob=new Scanner(System.in);
System.out.println("Enter the months,dates and years");
m1=ob.nextInt();
m2=ob.nextInt();
d1=ob.nextInt();
d2=ob.nextInt();
y1=ob.nextInt();
y2=ob.nextInt();
for(i=y1;i<y2;i++)
{
ob.leap(i+1)
m=1*diy;
s1=s1+m;
}
for(i=1;i<m1;i++)//no of days left in y1
{
ob.leap(y1);
s2+=a[i];
}
s2+=d1;
k=diy-s2;
for(i=1;i<m2;i++)//no of days passed
{
ob.leap(y2);
s3+=a[i];
}
s3+=d2;
s=s1+s2+s3;
System.out.println("No of days in between"+s)
}
}
Please help.
Your program is a bunch of errors. First, you are calling class variables in main method without declaring them static or initializing them in constructor. Second, you are calling leap() which is method of a class from object of Scanner. It is not possible. The program will never compile nor run this way. I have modified your code to make it compilable and runnable. But one thing is for sure. Its logic is incorrect. It is giving wrong output as you want to calculate number of days between two dates. That is your job. I removed its errors. Now it is running. Here you are :-
import java.util.*;
class yearst
{
static int a[]={0,31,28,31,30,31,30,31,30,31,30,31,30};
static int i=1,s,s1=0,s2=0,s3=0,k,diy=365,m,m1,m2,d1,d2,y1,y2,y;
static void leap(int y)
{
if(y%4==0 && y%100!=0 || y%400==0) //for leap year
{
a[2]=29;
diy=366;
}
else
{
a[2]=28;
diy=365;
}
}
public static void main(String args[])
{
//i=1;s1=0;s2=0;s3=0;diy=365;
Scanner ob=new Scanner(System.in);
System.out.println("Enter the months,dates and years");
m1=ob.nextInt();
m2=ob.nextInt();
d1=ob.nextInt();
d2=ob.nextInt();
y1=ob.nextInt();
y2=ob.nextInt();
for(i=y1;i<y2;i++)
{
leap(i+1);
m=1*diy;
s1=s1+m;
}
for(i=1;i<m1;i++)//no of days left in y1
{
leap(y1);
s2+=a[i];
}
s2+=d1;
k=diy-s2;
for(i=1;i<m2;i++)//no of days passed
{
leap(y2);
s3+=a[i];
}
s3+=d2;
s=s1+s2+s3;
System.out.println("No of days in between"+s);
}
}
All the Best :)
Only declarations and static blocks allowed out of the methods. The below executable statement must be either in static block or in constructor
int i=1,s1=0,s2=0,s3=0,diy=365;
So, I recommend you move above code to constructor.
yearst(){
i=1;s1=0;s2=0;s3=0;diy=365;
}
A few things:
You'll need to initialize your variables inside a constructor, as initializing inside a class isn't allowed
Have you checked out the Date class in Java? It might be more useful for this case.
According to convention, class names should start with a capital letter

I keep running into the same problems every time I try to make a new program

My current program is a simple game.. I am trying to make it to help figure out how to properly use OOP. But every time I get a little bit into a new program I run into the same problem:
I make an instance to use in my game. This instance could be anything - the main hero, a monster, whatever. Everything is going good, the instance is exactly what I want it to be. Maybe I manipulate it a little bit.
I then try to use a different class, I guess I create an instance of a different class, in an attempt to further manipulate the original instance. Maybe I originally created my hero and changed his stats, and now at this point I am trying to have my hero say something based on the stats that were chosen.
This point is always where I hit a roadblock. I can't seem to do what I want to do here - I can't use that original instance I made because It was just an instance and I don't know how to manipulate it(or even if I am supposed to) from within a new class.
So.. it's a fundamental design problem/lack of understanding of OOP.
But I feel like I have a decent grasp on how to actually program stuff.. I keep reading and reading and getting advice but I can't seem to get past this barrier.
I know people on this site don't seem to like posts like this but maybe someone here can Identify with what it is I am not grasping.
Here is an example of what I am talking about, the game I am trying to make right now.
package pkgnew.stupid.game;
import java.util.Scanner;
/**
*
* #author whyguy2
*/
public class Hero {
public static int heroattack = 1;
public static int herospeed = 1;
public static int heroarmorpen = 1;
public static int heroarmor = 1;
public static int herohealth = 5;
public static String inputstat;
public static int herothepoints = 0;
Hero(int points){
spendpoint(points);
}
public void attack(){
}
public void die(){
System.exit(0);
}
public void winbattle(){
System.out.println("You win the battle and have one new point to spend!");
spendpoint(1);
new NewEncounter();
}
public void levelup(){
System.out.println("You have leveled up and receive 5 new points to spend");
spendpoint(5);
new NewEncounter();
}
public void spendpoint(int points){
for(int x=0; x<points; x++){
System.out.println("Available Points: " + points);
System.out.println("Available Attributes:");
System.out.println("attack: " + heroattack);
System.out.println("speed: " + herospeed);
System.out.println("armorpen: " + heroarmorpen);
System.out.println("armor: " + heroarmor);
System.out.println("health: " + herohealth);
System.out.println(points);
System.out.println(x);
Scanner keyboard = new Scanner( System.in );
inputstat = keyboard.next( );
if(inputstat.equals("attack")){
heroattack = heroattack + 1;
}
else if(inputstat.equals("speed")){
herospeed = herospeed + 1;
}
else if(inputstat.equals("armorpen")){
heroarmorpen = heroarmorpen + 1;
}
else if(inputstat.equals("armor")){
heroarmor = heroarmor + 1;
}
else if(inputstat.equals("health")){
herohealth = herohealth + 5;
}
else{
System.out.println("Please pick one of the stats");
x = x-1;
}
}
}
}
public class StartGame {
StartGame(){ //runs through output for a new game
System.out.println("Welcome to the game");
System.out.println("Pick your hero's starting stats");
Hero thishero = new Hero(10); //spends your points
System.out.println("Let's Begin!/n/n");
new NewEncounter(); //goes into the encounter loops
}
}
at this point I I try to program an encounter in the NewEncounter class, but that isn't possible because I can't use that instance of my hero that I created. and I am pretty sure that my design is bad in the first place, I think I have read that you should be trying to use static variables as little as possible in the first place. I am still reading trying to grasp this but I have read a lot and I feel like nothing is helping me. I actually think a more "hands on" large scale project/tutorial might help me, but I don't know one. Anyways thanks for any help and sorry for the long/blog-like post.
The standard way to use an instance of one class within another is to either store a reference to it or to pass it into the method that stores or uses it.
For example:
class Encounter {
private final Hero mainHero;
private final List<Hero> participants;
public Encounter(Hero mainHero) {
this.mainHero = mainHero;
participants = new ArrayList<>();
}
public void addParticipant(Hero hero) {
participants.add(hero);
}
}
Allows:
Encounter encounter = new Encounter(hero);
or:
encounter.addParticipant(hero);
These can then be used within the class. For example:
class Encounter {
public void moveAllParticipants() {
participants.forEach(Hero::move);
}
}
I notice you have used a lot of public static class variables. This is unusual and there are few good reasons to use them. One is to define constants. If that's your intent then I suggest you use the following standard form:
private static final int HERO_ATTACK = 1;
If you intend for these to be instance variables (i.e. different for each hero) then they should not be static nor public.
This is the sort of area that is well covered in the various Java tutorials. I suggest working through one of them and coming back here if you have further issues.

Categories

Resources