Hello all, as I continue coding, I have gone back over some code that I wanted to encapsulate. I made all my instance variables private and made a lot of new public methods that would be used to set and get my instance variables. While I don't have any particular question about encapsulation, I was hoping anyone could read over my most recent code and offer any tips/suggestions so that I am not practicing bad habits.
Its rather hard to kill a bad habit if you do it a lot.
Thanks!
public class player{ private int health = 100; private char sex; private String name; private static short damage = 10; private static int hitchance; public void attack(){ //First decides if they hit or not... setHitchance(); if (getHitchance() >= 6){ System.out.println(name + " prepares for an attack..."); System.out.println(name + " unleashes the attack for " + getDamage() + " damage!"); health = health - damage; } else{ System.out.println(name + " missed!"); } } public void die(){ System.out.println(name + " has died"); System.out.println(name + " loses"); } public void setHitchance(){ hitchance = (int) (Math.random() * 10); } public int getHitchance(){ return hitchance; } public void setSex(char maleOrFemale){ sex = maleOrFemale; } public char getSex(){ return sex; } public int getHealth(){ return health; } public void setName(String NameA){ name = NameA; } public String getName(){ return name; } public int getDamage(){ return damage; } }
Another Class...
public class fightGame { player fighter1 = new player(); player fighter2 = new player(); public void introFight() { fighter1.setSex('m'); fighter2.setSex('m'); fighter1.setName("Lig"); fighter2.setName("Bone"); System.out.println("\nWelcome one and all to the grand fighting arena!"); System.out.println("Today we will see the fight off between the one and only: " + fighter1.getName() + " and " + fighter2.getName()); System.out.println("\n"); } public void startFight() { System.out.println(fighter1.getHealth() + " " + fighter2.getHealth()); while (fighter1.getHealth() > 0 & fighter2.getHealth() > 0) { fighter1.attack(); fighter2.attack(); System.out.println(fighter1.getName() + "'s health is now: " + fighter1.getHealth()); System.out.println(fighter2.getName() + "'s health is now: " + fighter2.getHealth()); } if (fighter1.getHealth() <= 0){ fighter1.die(); } else{ fighter2.die(); } } }