What does Java static object mean? - java

What is the advantage if we make object as static? Seeking detailed explanation !!

Well you can make a Variable static, and this Var is refering to an Object, Why would it be good? well a static means that it will be visible to all aplication (well also depends of its package visibility, public, protected, default, private)
Why would be good? well maybe you're creating an "static object" in order to use it in diferent objects for example a game, look i made one ("of course it is an example")
public class Dummy {
static Player player = new Player("Yussef");
public static void main(String[] args) {
stageOne();
satageTwo();
}
static void stageOne(){
System.out.println("Ready? Go");
System.out.println(player);
System.out.println("Ouch an enemy hit me");
player.setLife(80);
System.out.println(player);
}
static void satageTwo(){
System.out.println("Good, now you're in next level");
System.out.println(player);
System.out.println("Ouch an enemy hit me");
System.out.println("Ouch an enemy hit me");
player.setLife(40);
System.out.println(player);
}
}
class Player{
private String name;
private int life;
Player(String name){
this.name = name;
life = 100;
}
#Override
public String toString() {
return "My name is: "+name+" And mi actual life is: "+life;
}
public void setLife(int life) {
this.life = life;
}
}
Now Imagine inspite of using the same class, i would've made more Clases, or more players, well the poit is this: My player will have the same life in all my game, and same name, so no matter what stage i play i will have the same attributs or changed them maybe ;).
It is an example i thought, hope it could help u

Related

So I am lost in creating classes, private/public variables, get/set functions, and more in Java

So this is the first part of my assignment:
Create a new java class called "House".
Add constructor without parameters and add a system out put of your choice
Add 4 Private Member Variables
an integer that represents the number of rooms
a String that represents the address
a boolean that represents if the house is for sale
a double that represents the value of the house
Add a Get and Set functions for ALL 4 member variables
In my house code I think this is the right way to do it:
public class House {
private int Rooms;
private String Address;
private double Value;
private boolean Sale;
public House() {
System.out.println("CONSTRUCTOR EXECUTED");
}
public void setRooms(int Rooms) {
this.Rooms = Rooms;
}
public int getRooms () {
return Rooms;
}
public void setAddress (String Address){
this.Address = Address;
}
public String getAddress() {
return Address;
}
public void getValue(double Value) {
this.Value = Value;
}
public double setValue() {
return Value;
}
public void getSale(boolean Sale) {
this.Sale = Sale;
}
public boolean getSale() {
return Sale;
}
}
For the second part, which I'm more confused about, is says this:
Create a Main Class and add the static main function
Initialize Main and add a start function
In the start function create new House object
Call all 4 Set functions
Output all 4 Get Functions
Example Output "The House has '4' rooms located at 'address' and is or is not for sale'
If the house is for sale, out the value of the house
So I created the Main file and I think I have the start up correct but I don't know how to print it all out. This is what I at least have so far:
public class Main {
public static void main(String[] arg) {
}
private void start() {
House rooms = new House ();
}
}
I definitely do not want the answer, just some pointers in the right direction.
Looking at the instructions, I don't think you need to create a separate Main class. I think when it says 'Initialize Main' it just means add the main method to the House class.
Additionally, the way you have it now is not going to work properly. start() will not be able to be called from the main method, since main is static and start is not.
My feeling is that the best way to go about it would be to put main and start in the House class. Then, you can initialize an instance of House in the main method, and then call start on that instance. From there, start can perform the rest of the instructions.
Hope this helps.

Getting Variables From Java constructor

I'm new to Java programming, sorry if this is a dumb question.
I find it hard to word this question properly, but I have an assignment to create a aircraft class that can make aircraft land, takeoff etc. And need to test it using Testclass. When the new object are entered it automatically assigns a unique ID to the aircraft in the constructor.
I can do this using a instance method fine as it has a return value which is returned to to Testclass. The question wants me to do this in the constructor itself, however, the constructor never returns anything. So the variable never gets sent to the Testclass. I clearly am not understanding OOP properly. Even when I try to just use a getter method to get the ID created in the constructor it gives me the initialized variable before the the constructor has worked on this. This is the code I have so far and its completely wrong I know but if someone could point me in the right direction or tell me how to word this question better it would be a massive help.
// I need to enter 3 aircraft into the system in the testclass
public class Aircraft {
private int aircraftID;
private static int lastID;
private String airportcode;
private int ID = 100;
private int count;
public Aircraft(int a, int b, int c){
// Constructor
// Assign ID
this.ID = a;
lastID = ID;
ID++;
this.ID =b;
lastID = ID;
ID++;
}
}
OK, you want to create an Aircraft that has an automatically-assigned unique identifier, and can take off and land. That implies you need a field for tracking the identifier, a field for tracking whether it's in the air (or not), and methods for the take off and land operations. You also need a static field for generating the unique identifiers. (Note that this implementation isn't thread safe.)
private class Aircraft {
private static int staticId = 0;
private int uniqueId = 0;
private boolean onGround = true; // Aircraft start on the ground in this implementation
public Aircraft(){
this.uniqueId = staticId; // putting this line first makes uniqueId zero-indexed in effect
staticId++;
}
public void land(){
onGround = true;
}
public void takeoff(){
onGround = false;
}
public boolean isFlying(){
return !onGround; // If it's not on the ground, it's flying
}
public int getUniqueId(){
return uniqueId;
}
}
Unit tests checks all of the methods and expected functionality of the class in question:
import org.junit.Test;
import static org.junit.Assert.*;
import Aircraft;
class Testclass {
private final Aircraft aircraft = new Aircraft();
#Test
public void hasId(){
aircraft.getUniqueId() >= 0;
}
#Test
public void canLand(){
assertTrue(aircraft.land());
}
#Test
public void canTakeOff(){
assertTrue(aircraft.takeOff());
}
#Test
public void checkFlightOperationsAreTrackedCorrectly(){
aircraft.land();
assertFalse(aircraft.isFlying());
aircraft.takeOff();
assertTrue(aircraft.isFlying());
}
}
As pointed out a constructor does not return anything (the simplified version is that with new it returns an object instance). I am kinda guessing at what you are trying to acomplish, but I'll have a go anyways. It seems to me that you are trying to cram the construction of 3 objects into one constructor - which is why your constructor has 3 parameters. Also you are playing havoc with the IDs.
I have removed all the variables that I didnt quite understand, leaving only ID that increments with each instantiated Aircraft. The #Override is mainly just for show.
public class Aircraft {
private int aircraftID;
private static int lastID = 0;
#Override
public String toString(){
return "Aircraft_" + this.aircraftID;
}
public Aircraft() {
lastID++;
this.aircraftID = lastID;
}
}
I took the liberty and wrote the TestClass just to see if we have the same thing in mind. Again the printAircraft() method is for show.
public class TestClass {
private List<Aircraft> aircrafts;
public TestClass(){
aircrafts = new ArrayList<>();
}
public void addAircraft(Aircraft a){
aircrafts.add(a);
}
public void printAircraft(){
Iterator<Aircraft> it = aircrafts.iterator();
while(it.hasNext()){
System.out.println(it.next().toString());
}
}
}
and to test it, we create and instance of TestClass add 3 Aircraft instances and print out the contents
public static void main(String[] args) {
TestClass tc = new TestClass();
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.addAircraft(new Aircraft());
tc.printAircraft();
}
This would be the case if you are to write the TestClass. If that is given, it would help to know what it looks like - maybe that would help us understand better.

Java: Read, edit and create a text file

I have a Java program that creates Swords. Now, I want to store the damagevalue and name of these Swords in a text file, and be able to read these values later. What is the best way to do that?
I have two classes:
Sword.java and NewSword.java, where NewSword.java is the function to create a new sword (o.O). Here's the code:
Sword.java:
package game;
public class Sword {
public static int numberOfSwords=0;
public static void main(String [] args){
functions.NewSword.newSword("Wooden Sword", 2);
System.out.println(numberOfSwords);
}
}
and
NewSword.java:
package functions;
public class NewSword {
public static void newSword(String nameSword, int damageSword){
game.Sword.numberOfSwords++;
}
}
So:
I wish to be able to, in the function newSword(String nameSword, int damageSword), put the nameSword and the damageSword in a text file, and be able to read that... So that I can later do like: "He has a wooden sword, what's the damage?"... I want to put it in a text file, because I want to know how that works, and practice with it. Also, I think it makes it easier if I want to add features to swords, and can put those in text files as well... Hope you can help me!
EDIT: I put the function in another package, that's why it's functions.NewSword.newSword("Wooden Sword", 2);, just for the heck of it :D But also to be a bit organized...
Read throught this: http://www.tutorialspoint.com/java/java_files_io.htm
It explains everything in from creating a file to reading it and will sure help you out.
However regard kviiris commend about learning something about object oriented programming.
Heres the basic approach for your swords:
You write a class for your sword that contains all the information you need for a given sword.
public class Sword {
private String name;
private int damage;
// this is the constructor to create new swords
public Sword(String name, int damage){
this.name = name;
this.damage = damage;
}
}
Now you can access this from your main class and use it to create as many swords as you want simply with
Sword s = new Sword("wooden sword", 2);
Sword s2 = new Sword("iron sword", 20);
Note: you used the same class (Sword) but this are still 2 completely separate swords.
Thats the main use of object oriented programming.
This will compile.
Game.java
package game;
import functions.Sword;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class Game {
List<Sword> swords = new ArrayList<Sword>();
public static void main(String[] args) {
Game game = new Game();
game.play();
}
public void play() {
swords.add(new Sword("Wooden sword", 2));
swords.add(new Sword("Silver sword", 4));
System.out.println(swords.size());
System.out.println(Arrays.toString(swords));
}
}
Sword.java
package functions;
public class Sword {
private final String name;
private final int damage;
public Sword(String name, int damage) {
this.name = name;
this.damage = damage;
}
public String getName() {
return name;
}
public int getDamage() {
return damage;
}
}

Adding new objects to an ArrayList in constructor

I am trying to add newly created objects to an ArrayList in the constructor of a class. The new objects are being created in another class in the main method.
Main method:
public static void main(String[] args) {
// TODO code application logic here
Player p1 = new Player("Peter");
}
My Player class:
public class Player {
protected static int age;
protected static String name;
protected static ArrayList players = new ArrayList();
Player(String aName) {
name = aName;
age = 15;
players.add(new Player()); // i know this doesn't work but trying along these lines
}
}
You have to edit the line
players.add(new Player());
to
players.add(this);
Also, there is no need to make the age and name static
I suggest you should have the following code instead
import java.util.ArrayList;
public class Player {
protected int age; //static is removed
protected String name; // static is removed
protected static ArrayList<Player> players = new ArrayList<Player>(); //this is not a best practice to have a list of player inside player.
Player(String aName) {
name = aName;
age = 15;
players.add(this); // i know this doesn't work but trying along these lines
}
public static void main(String[] args) {
// TODO code application logic here
Player p1 = new Player("Peter");
}
}
It sounds like you're actually asking how to refer to the instance you're constructing.
That's what the this keyword does.
This post is old, but for someone with similiar needs I suggest doing it like this:
Main class:
public static void main(String[] args) {
//TODO code application logic here
java.util.List<Player> players = new java.util.ArrayList<>(); //list to hold all players
Player p1 = new Player("Peter"); //test player
players.add(p1); //adding test player to the list
players.add(new Player("Peter")); //also possible in this case to add test player without creating variable for it.
}
Player class:
public class Player {
private final int age = 15; //if you always going to use 15 as a age like in your case it could be final. if not then pass it to constructor and initialize the same way as the name.
private String name;
Player(String name) { //variable name can be the same as one in class, just add this prefix to indicated you are talking about the one which is global class variable.
this.name = name;
}
}
Generally you should avoid using static keyword on variables which supposed to be different in each instance of that class. Avoid having object of itself inside.

Java-How do I call a class with a string?

I am a beginner programmer and this is my first question on this forum.
I am writing a simple text adventure game using BlueJ as a compiler, and I am on a Mac. The problem I ran into is that I would like to make my code more self automated, but I cannot call a class with a string. The reason I want call the class and not have it all in an if function is so that I may incorporate more methods.
Here is how it will run currently:
public class textadventure {
public method(String room){
if(room==street){street.enterRoom();}
}
}
public class street{
public enterRoom(){
//do stuff and call other methods
}
}
The if statement tests for every class/room I create. What I would like the code to do is automatically make the string room into a class name that can be called. So it may act like so:
Public method(string room){
Class Room = room;
Room.enterRoom();
}
I have already looked into using Class.forName, but all the examples were too general for me to understand how to use the function. Any help would be greatly appreciated, and if there is any other necessary information (such as more example code) I am happy to provide it.
-Sebastien
Here is the full code:
import java.awt.*;
import javax.swing.*;
public class Player extends JApplet{
public String textOnScreen;
public void start(){
room("street1");
}
public void room(String room){
if(room=="street1"){
textOnScreen=street1.enterRoom();
repaint();
}
if(room=="street2"){
textOnScreen=street2.enterRoom();
repaint();
}
}
public void paint(Graphics g){
g.drawString(textOnScreen,5,15);
}
}
public abstract class street1
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on a street running from North to South.";
return textToScreen;
}
}
public abstract class street2
{
private static String textToScreen;
public static String enterRoom(){
textToScreen = "You are on another street.";
return textToScreen;
}
}
Seeing as you are rather new to programming, I would recommend starting with some programs that are simpler than a full-fledged adventure game. You still haven't fully grasped some of the fundamentals of the Java syntax. Take, for example, the HelloWorld program:
public class HelloWorld {
public static void main(String[] args) {
String output = "Hello World!"
System.out.println(output);
}
}
Notice that public is lowercased. Public with a capital P is not the same as public.
Also notice that the String class has a capital S.* Again, capitalization matters, so string is not the same as String.
In addition, note that I didn't have to use String string = new String("string"). You can use String string = "string". This syntax runs faster and is easier to read.
When testing for string equality, you need to use String.equals instead of ==. This is because a == b checks for object equality (i.e. a and b occupy the same spot in memory) and stringOne.equals(stringTwo) checks to see if stringOne has the same characters in the same order as stringTwo regardless of where they are in memory.
Now, as for your question, I would recommend using either an Enum or a Map to keep track of which object to use.
For example:
public class Tester {
public enum Location {
ROOM_A("Room A", "You are going into Room A"),
ROOM_B("Room B", "You are going into Room B"),
OUTSIDE("Outside", "You are going outside");
private final String name;
private final String actionText;
private Location(String name, String actionText) {
this.name = name;
this.actionText = actionText;
}
public String getActionText() {
return this.actionText;
}
public String getName() {
return this.name;
}
public static Location findByName(String name) {
name = name.toUpperCase().replaceAll("\\s+", "_");
try {
return Enum.valueOf(Location.class, name);
} catch (IllegalArgumentException e) {
return null;
}
}
}
private Location currentLocation;
public void changeLocation(String locationName) {
Location location = Location.findByName(locationName);
if (location == null) {
System.out.println("Unknown room: " + locationName);
} else if (currentLocation != null && currentLocation.equals(location)) {
System.out.println("Already in room " + location.getName());
} else {
System.out.println(location.getActionText());
currentLocation = location;
}
}
public static void main(String[] args) {
Tester tester = new Tester();
tester.changeLocation("room a");
tester.changeLocation("room b");
tester.changeLocation("room c");
tester.changeLocation("room b");
tester.changeLocation("outside");
}
}
*This is the standard way of formating Java code. Class names are PascalCased while variable names are camelCased.
String className=getClassName();//Get class name from user here
String fnName=getMethodName();//Get function name from user here
Class params[] = {};
Object paramsObj[] = {};
Class thisClass = Class.forName(className);// get the Class
Object inst = thisClass.newInstance();// get an instance
// get the method
Method fn = thisClass.getDeclaredMethod(fnName, params);
// call the method
fn.invoke(inst, paramsObj);
The comments below your question are true - your code is very rough.
Anyway, if you have a method like
public void doSomething(String str) {
if (str.equals("whatever")) {
// do something
}
}
Then call it like
doSomething("whatever");
In Java, many classes have attributes, and you can and will often have multiple instances from the same class.
How would you identify which is which by name?
For example
class Room {
List<Monster> monsters = new ArrayList <Monster> ();
public Room (int monstercount) {
for (int i = 0; i < monstercount; ++i)
monsters.add (new Monster ());
}
// ...
}
Monsters can have attributes, and if one of them is dead, you can identify it more easily if you don't handle everything in Strings.

Categories