I don't understand private variables? - java

There is nothing wrong with the code, but I don't understand why you have to create a private String name, and then equals that string with the string from method i.e. name = n.
public class Person {
private String name;
public Person (String n) {
name = n;
}
public String getName() {
return name;
}
public boolean sameName(Person other) {
return getName().equals(getName());
}
}

A private variable can't be accessed from outside the class, but only by the methods inside the class so it's safer

Related

Defining class field and calling parent's constructor

These are two classes of code that I wrote.. the problem here is I am not sure how to define class fields to represent Grass, fire and water as a Type using static..
Also I am not sure if I had used the super function the right way.. How do I properly call the parent's constructor so that I dont have to re define "knockedOut boolean" and be able to use Fire as the type?
Question could be confusing but I am not sure how to explain it better :( sorry
public abstract class Pokemon {
private String name;
private String type;
private int attack;
private int health;
private boolean knockedOut;
static private String Grass;
static private String Water;
static private String Fire;
public Pokemon (String n, String t, int a, int h) {
name = n;//state
type = t;//state
attack = a;//state
health = h;//state
knockedOut = false;
}
public abstract int takeDamage(Pokemon enemy);
public String toString() {
return "}";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public int getAttack() {
return attack;
}
public void setAttack(int attack) {
this.attack = attack;
}
public int getHealth() {
return health;
}
public void setHealth(int health) {
this.health = health;
}
public boolean isKnockedOut() {
return knockedOut;
}
public void setKnockedOut(boolean knockedOut) {
this.knockedOut = knockedOut;
}
}
public abstract class Charizard extends Pokemon {
private static String Fire;
private int attackFire;
private int healthFire;
private static String Water;
private static String Grass;
public Charizard(int a, int h) {
super("Charizard", Fire, a, h);
attackFire = a;
healthFire = h;
}
public int takeDamage(Pokemon enemy){
int enemyAttack = enemy.getAttack();
if(enemy.getType().equals(Water)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()*2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
}
else if(enemy.getType().equals(Fire)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()*2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
}
else if(enemy.getType().equals(Grass)){
enemy.setHealth(enemy.getHealth()-attackFire/2);
healthFire = healthFire-enemy.getAttack()/2;
if(enemy.getHealth()<=0){
enemy.setKnockedOut(true);
}
if(healthFire <=0){
Charizard.set = true;
}
}
return enemyAttack;
}
}
You want to declare your different types like this:
static public final String GRASS= "Grass";
static public final String WATER = "Water";
static public final String FIRE = "Fire";
(I'm following the established convention here that fields declared static, public, and final should have names in all uppercase letters.)
By declaring these fields public, any other classes (including those that extend Pokemon, such as Charizard) that might need to test the type of a Pokemon can use them. By declaring them final, nobody can change them even though they are public. By giving them initial values, you make them actually useful for distinguishing different types of Pokemon, as well as avoid the inevitable NullPointerException that would happen the first time you executed something like p.getType().equals(Pokemon.FIRE)
As for knockedOut, it looks like you're handling it the right way. The field knockedOut is private in Pokemon but you've provided public getter and setter methods that other classes can (and do) use to access it.

Serializing an Arraylist<CustomObject>

I have created an Object called "Item", and I want to serialize an ArrayList with Items inside it. My program works perfectly with an ArrayList<String>, but it doesn't work with an ArrayList<Item>. I believe it has to do with my Object. Here it is:
public class Item implements Serializable{
private static String name;
private static BufferedImage picture;
private static boolean craftable;
private static Item[][] craftTable;
private static boolean smeltable;
private static Item smelt_ancestor;
private static Item smelt_descendant;
public Item(String name, boolean craftable, boolean smeltable){
this.name = name;
this.craftable = craftable;
if(craftable){
craftTable = new Item[3][3];
}else{
craftTable = null;
}
this.picture = null;
this.smeltable = smeltable;
this.smelt_ancestor = null;
this.smelt_descendant = null;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public BufferedImage getPicture(){
return picture;
}
public boolean setPicture(){
boolean verify = false;
String pictureName = name.replaceAll("\\s+","");
String newNamePng = pictureName + ".png";
String newNameJpg = pictureName + ".jpg";
File imagePng = new File(newNamePng);
File imageJpg = new File(newNameJpg);
if(imagePng.exists()){
return true;
}else if(imageJpg.exists()){
return true;
}else{
return false;
}
}
public boolean getCraftable(){
return craftable;
}
public void setCraftable(boolean value){
this.craftable = value;
}
public boolean setCraftTable(Item[][] table){
if(this.craftable==true){
craftTable = table;
return true;
}else{
return false;
}
}
public Item[][] getCraftTable(){
return craftTable;
}
public boolean getSmeltable(){
return smeltable;
}
public void setSmeltable(boolean value){
smeltable = value;
}
public Item getAncestor(){
return smelt_ancestor;
}
public void setAncestor(Item ancestor){
smelt_ancestor = ancestor;
}
public Item getDescendant(){
return smelt_descendant;
}
public void setDescendant(Item des){
smelt_descendant = des;
}
public String toString(){
return name;
}
Ignore the imports, I use them in other methods I omitted because they work perfectly. Is there anything wrong with the Object that could stop it from being serialized correctly?
Static variables are not serialized. It looks like you probably want those to be non-static instance variables.
Serialization by definition is applied on objects and not classes.
It copies the state of an object to be transferred over a network or a stream or to be stored.
Your usage of static variables make them class variables, and hence they do not contribute to the state of an object. First thing to do would be make them non-static.
This leaves us with your class, which is already Serializable and so is ArrayList. You can just serialize them and de-serialize them using ObjectInputStream and ObjectOutputStream and by making sure you have the same class in the classpath at the Deserialization end.

Can a static final field be initialized in subclasses? If so, how?

I need to write some code which is as follows:
public class Person {
public static final String NAME;
public Person(String NAME) {
this.NAME = NAME;
}
}
public class Player extends Person {
public Peter(String name) {
super(name);
}
}
It's basically, I want the Player class to have a static final field called NAME, that is being initialized somewhere else, without manually writing in every class public static final String NAME = "Peter".
Is it possible?
As it has been said in the comments, you have poorly declared your NAME variable. In actuality, you don't want it to be static (although you can keep the final modifier, if you want). Your code should, instead, be something along the lines of:
public class Person {
public final String name;
public Person(String name) {
this.name = name;
}
}
public class Player extends Person {
public Player(String name) {
super(name);
}
}
Every person should have their own name; you don't want all objects to be sharing one NAME field
I do not know if I fully understand your question, but I think you have a few mistakes in your code. Like declare name of person as static variable, because static variables are often used as variables for the entire class, and if you changed the name, would change the name to the entire class, not for one instance. Also final is wrong, because you cannot set final variable.
I would do something like this:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return String.format("Person: %s", this.getName());
}
}
public class Player extends Person{
public Player(String name) {
super(name);
}
public String toString(){
return String.format("Player: %s", this.getName());
}
}
public class Match {
private Player player_one;
private Player player_two;
public Match(Player player_one, Player player_two) {
this.player_one = player_one;
this.player_two = player_two;
}
public Player getPlayer_one() {
return player_one;
}
public void setPlayer_one(Player player_one) {
this.player_one = player_one;
}
public Player getPlayer_two() {
return player_two;
}
public void setPlayer_two(Player player_two) {
this.player_two = player_two;
}
#Override
public String toString() {
return String.format("Right now are playing %s VS %s",player_one.getName(), player_two.getName());
}
}
public class PlayerTest {
public static void main(String[] args) {
Player peter = new Player("Peter");
Player anna = new Player("Anna");
Match tennisMatch = new Match(peter, anna);
System.out.println(tennisMatch.toString());
}
}
I static field (variable) only exists once for all instances of your class. Therefore what you try does not work by design.
What value would you expect the field to have after you created three different instances of this class using different parameters?
A final variable cannot be changed once it got initialized. For static variables this happens before the first instance of the class is even constructed. At the moment the constructor is executed the field cannot be changed anymore.
To initialize a static final variable you have to assign a value directly at the definition using the = operator or you have to do it in a static initializer which looks like this:
public class FooBar {
public static final String STATIC_VARIABLE;
static {
STATIC_VARIABLE = "Hello World";
}
}
You can make it like this:
private static final NAME;
public Player(String name){
NAME = name;
}
A final varible can be initialized once only if it wasn't initialized yet.
So in this way the constructor is helping you make it.

Java Subclasses last instance overwriting values

I'm a web developer dabbling in Java (again) and I'm having trouble with something.
Basically, I have a superclass Employee with two subclasses that extend it called Management and Programmer. The Employee class contains an array employees that is basically an array of Employee objects.
Here's the important snippets of two of the classes (Employee and Management) and the final main method. I'll explain the output at the bottom.
public class **Employee** {
private static String firstName;
protected static int MAXEMPLOYEES = 5;
protected Employee[] employees = new Employee[MAXEMPLOYEES];
protected int totEmployees = 0;
public Employee(String first) {
setFirstName(first);
}
public void setFirstName(String str){
firstName = str;
}
public String getFirstName(){
return firstName;
}
public boolean addEmployee(String fname) {
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
Employee empl = new Employee(fname);
employees[totEmployees] = empl;
added = true;
totEmployees++;
}
return added;
}
}
public class **Management** extends **Employee** {
private String title = "Project Manager";
public Management(String fname, String t){
super(fname);
title = t;
}
public boolean addManagement(String fname, String t){
boolean added = false;
if (totEmployees < MAXEMPLOYEES) {
employees[totEmployees] = new Management(fname, t);
added = true;
totEmployees++;
}
return added;
}
}
-------------------------------------
package employee;
public class EmployeeApplication {
public static void main(String[] args) {
Employee[] empl = new Employee[3];
empl[0] = new Employee("Kyle");
empl[1] = new Management("Sheree", "Director");
System.out.println(empl[0].getFirstName());
}
}
Now, I expect the system to print out "Kyle", but it prints out "Sheree". Any ideas???
private static String firstName;
You made firstName static, which means all instances share the same name. You'll need to remove the static modifier in order for different Employees to have different names. You'll also need to change the private access modifier to protected in order for the field to be inherited by subclasses.
private String firstName;
remove static;
Kyle was overridden by Sheree, that is why you are getting that output

create a class to model a list

I have a class named Person.This class represents (as the name says) a Person. Now I have to create a class PhoneBook to represent a list of Persons. How can I do this? I don't understand what means "create a class to represent a list".
import java.util.*;
public class Person {
private String surname;
private String name;
private String title;
private String mail_addr;
private String company;
private String position;
private int homephone;
private int officephone;
private int cellphone;
private Collection<OtherPhoneBook> otherphonebooklist;
public Person(String surname,String name,String title,String mail_addr,String company,String position){
this.surname=surname;
this.name=name;
this.title=title;
this.mail_addr=mail_addr;
this.company=company;
this.position=position;
otherphonebooklist=new ArrayList<OtherPhoneBook>();
}
public String getSurname(){
return surname;
}
public String getName(){
return name;
}
public String getTitle(){
return title;
}
public String getMailAddr(){
return company;
}
public String getCompany(){
return position;
}
public void setHomePhone(int hp){
homephone=hp;
}
public void setOfficePhone(int op){
officephone=op;
}
public void setCellPhone(int cp){
cellphone=cp;
}
public int getHomePhone(){
return homephone;
}
public int getOfficePhone(){
return officephone;
}
public int getCellPhone(){
return cellphone;
}
public Collection<OtherPhoneBook> getOtherPhoneBook(){
return otherphonebooklist;
}
public String toString(){
String temp="";
temp+="\nSurname: "+surname;
temp+="\nName: "+name;
temp+="\nTitle: "+title;
temp+="\nMail Address: "+mail_addr;
temp+="\nCompany: "+company;
temp+="\nPosition: "+position;
return temp;
}
}
Your PhoneBook class will likely have a member like this:
private List<Person> book = new ArrayList<Person>();
And methods for adding and retrieving Person objects to/from this list:
public void add(final Person person) {
this.book.add(person);
}
public Person get(final Person person) {
int ind = this.book.indexOf(person);
return (ind != -1) ? this.book.get(ind) : null;
}
Note that a List isn't the best possible representation for a phone book, because (in the worst case) you'll need to traverse the entire list to look up a number.
There are many improvements/enhancements you could make. This should get you started.
Based on the class being named PhoneBook, I assume that you ultimately want to create a mapping between a phone number, and a person. If this is what you need to do then your PhoneBook class should contain a Map instead of a List (but this may depend on other parameters of the project).
public class PhoneBook
{
private Map<String,Person> people = new HashMap<String,Person>();
public void addPerson(String phoneNumber, Person person)
{
people.put(phoneNumber,person);
}
public void getPerson(String phoneNumber)
{
return people.get(phoneNumber);
}
}
In the above, the phone number is represented as a String, which is probably not ideal since the same phone number could have different String representations (different spacing, or dashes, etc). Ideally the Map key would be a PhoneNumber class that takes this all into account in its hashCode and equals functions.
you can do it by creating a class PhoneBook
public class PhoneBook{
Private List<Person> personList = new ArrayList<Person>;
public void addPerson(Person person){
this.personList.add(person);
}
public List getPersonList(){
return this.personList;
}
public Person getPersonByIndex(int index){
return this.personList.get(index);
}
}

Categories