I'm currently stuck on a project. Here's what I should do:
Copy the Employee.java file from the java1_Lesson14 project to the java1_Project14 project. First, use what you've learned about encapsulation to protect your data.
Use a call to the System.out.println() method to display in the console the names and values of all of the instance variables in each instance of the Employee class. Also print to the console the value of any static variables.
Note that, if you access a static variable via an instance, Eclipse will warn you that this is not optimal behavior. Use the correct form for accessing and displaying any static information.
I think I did the encapsulation part right. The problem now is the warnings messages I'm getting from Eclipse.
On e2.setTopSalary(199000) I get the following message: "The static method setTopSalary(int) from the type Employee should be accessed in a static way."
And on System.out.println("e2 Top Salary is " + e2.topSalary): "The static field Employee.topSalary should be accessed in a static way."
Can anyone give me a light on how do I fix this?
public class Employee {
private static int topSalary = 195000;
private int hoursPerWeek;
public static void setTopSalary (int s) {
if (s > topSalary)
topSalary = s;
}
public void addMoreHours() {
hoursPerWeek++;
}
public static void main(String[] args) {
Employee e1, e2;
e1 = new Employee();
e2 = new Employee();
Employee.setTopSalary(199000);
e2.setTopSalary(199001);
e1.hoursPerWeek = 40;
e2.hoursPerWeek = 45;
System.out.println("Employee Top Salary is " + Employee.topSalary);
System.out.println("e2 Top Salary is " + e2.topSalary);
System.out.println("e1 working hours per week are " + e1.hoursPerWeek);
System.out.println("e2 working hours per week are " + e2.hoursPerWeek);
}
}
The static keyword means that all instances of the class still refer to one instance of the field. That field is effectively per-class.
You call it as follows:
Employee.setTopSalary(12000);
and access fields by:
System.out.println(Employee.topSalary);
Employee is the class name.
Related
I am a beginner in java and i am trying to understand the concept of static from a book I bought to learn java. But, because of my experiments in the program, I am very confused. The book says that static could not refer to this keyword, which is fine until I started using normal functions instead of static. In this, I was able to access the static variable with the this keyword!! (see the displayMobileSpecs function in the code below)
import java.util.Random;
class Static {
public static void main(String[] com){
System.out.println("By default the mobile is having "
+ Mobile.RAM + "gigabytes of RAM and"
+ Mobile.CameraMP + " mega pixels of camera");
Mobile S4mini = new Mobile("S4 Mini" , 4 , 16);
S4mini.displayMobileSpecs(true);
Mobile mob2 = new Mobile("fdf" , 23 , 45);
mob2.displayMobileSpecs(true);
S4mini.displayMobileSpecs(false);
}
}
class Mobile{
static int RAM;
static int CameraMP;
Random rand = new Random();
double InternalMemorySpace;
double ExternalMemorySpace;
String modelNo;
Mobile(String modelName,double internalMem , double externalMem)
{
this.modelNo = modelName;
this.InternalMemorySpace = internalMem;
this.ExternalMemorySpace = externalMem;
}
static {
RAM = 4;
CameraMP = 12;
System.out.println("The Static part of the class is executed");
}
void displayMobileSpecs(boolean change){
if(change)
this.RAM = (int) rand.nextInt(8) + 2;
System.out.println(this.RAM + " , " + Mobile.RAM);
}
}
So is it that static variables could be accessed using this but not in the static functions or what?? I am really confused and this is a very silly question as I see it, but please answer me.
(Note: by the way, please don't mind the ridiculous example of mobile used in the program. thanks :) )
static variables could be accessed using this but not in the static
functions
In static block or a static method, there is no instance to refer to, and therefore the "this" keyword is not permitted.
Why am i able to use this keyword with static variables in java
But you can refer "this" in a non static method also you can use refer static variable with "this" keyword in the non static method.Here "this" points to current object.
I'm very new to programming, and don't understand much. I've been trying to build a simple game where a user and computer compete by rolling dice to earn points. My method is posted below. The computer is only allowed to earn 20 points per turn.
My issue is that I need the value of variable computerTotal to be remembered after the method has been called and completed. I want to ensure that whenever the computerTurn method is finished, I can use that calculated variable computerTotal outside of that method.
I tried establishing a new int in the .java file class (but outside of the method), and then using that int within the method to hold the value, however I receive errors about the integer needing to be static?
This is all very confusing to me. Can anyone help me out?
public static void computerTurn()
{
System.out.println("Passed to Computer.");
Die computerDie1, computerDie2;
int computerRound, computerTotal;
computerRound = 0;
computerTotal = 0;
while (computerTotal < 21){
computerDie1 = new Die();
computerDie2 = new Die();
computerDie1.roll();
computerDie2.roll();
System.out.println("\n" + "CPU Die One: " + computerDie1 + ", CPU Die Two: " + computerDie2 + "\n");
computerRound = computerDie1.getFaceValue() + computerDie2.getFaceValue();
int cpuDie1Value;
int cpuDie2Value;
cpuDie1Value = computerDie1.getFaceValue();
cpuDie2Value = computerDie2.getFaceValue();
System.out.println ("Points rolled this round for the Computer: " + computerRound);
computerTotal = computerTotal + computerRound;
System.out.println ("Total points for the Computer: " + computerTotal + "\n");
}
Any variables created inside a method are "local variables" meaning they cannot be used outside the method. Put a static variable outside of a method to create "global variables" which can be used anywhere.
Add a method to your class
public static int getComputerTotal() { return ComputerTotal;}
Then you can get the value outside of the class by doing something like:
ComputerTurn();
ComputerTurn.getComputerTotal();
Putting the variable outside of the method is on the right track, but since this method is static (meaning it cannot access variables that depend on object instances), it can only access static variables. Declare computerTotal in the class, outside of methods, using the following:
private static int computerTotal;
You should probably do some research on object-oriented programming and what static means in Java.
Declare computerTotal as a member variable of your class, so that its value is available even outside the function.
class MyClass{
private int computerTotal ;
public void function myFunction()
{
........
......... // your calculations
computerTotal = computerTotal + computerRound;
}
public int getComputerTotal(){return computerTotal ;}
}
You have to declare the computertotal outside any methods to keep them. so like this:
public class name {
int computertotal = 0; //v=can just uuse int computertotal;
public void method() {
while(computertotal < 20) {
computertotal += 1;
}
}
}
And now he variable gets saved!
You may need to add some setters and getters to get that int from another class.
class NewClass {
private int yourInt = 1;
}
It is telling you to make it a static variable because you may be calling it in a statement like
NewClass.yourInt;
, a static variable is one that’s associated with a class, not objects of that class.
Setters and getters are methods which allows you to retrieve or set the value which is private from another class. You might want to add them in the NewClass, where your int is declared. Setters and getters looks like this.
Setter:
public void setYourInt(int newInt) {
this.yourInt = newInt;
}
Getter:
public int getYourInt() {
return this.yourInt;
}
In this book, there is this example of how to use static variables and methods. I dont understand what is going on. explain why there has to be static in front of the methods and variables. There are two seperate classes called Virus and VirusLab. The VirusLab.java takes in a command line argument and makes the amount of Virus objects, then spits out the number of Virus objects. Thanks
Virus:
public class Virus {
static int virusCount = 0;
public Virus() {
virusCount++;
}
public static int getVirusCount() {
return virusCount;
}
}
VirusLab:
public class VirusLab {
public static void main(String[] args) {
int numViruses = Integer.parseInt(args[0]);
if (numViruses > 0) {
Virus[] virii = new Virus[numViruses];
for (int i = 0; i < numViruses; i++) {
virii[i] = new Virus();
}
System.out.println("There are " + Virus.getVirusCount()
+ " viruses.");
}
}
}
A web search would have given you hundreds of links to explain 'static' keyword in Java.
Please refer to the following documentation: http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Also, please refer a text book for your further learning, that will help a lot.
I will keep it pretty short
You need static variables if you want that variable to be shared
across all the objects of your class,so that if one of the object
changes its value it would be reflected in other objects as well,which
is what is exactly done in above example.
A static variable is one which is not associated with an instance of a class.
This means you don't have to create a new instance of the class to access the variable from another class. Consider this:
public class Login {
public static String loggedInUser
public void setLoggedInUser(String name){
this.loggedInUser = name;
}
}
To access the String loggedInUser in another class, you wouldn't have to say
Login login = new Login();
String username = login.loggedInUser;
You'd just have to say
String username = Login.loggedInUser;
This can be useful in accessing variables outside of the class they were set in.
Hope that helps.
try reading this answer I gave in a previous question:
Accessing Static variables
and make google and wikipedia ur friend they'll save u time coming on here posting questions ,waiting and refreshing ur page to check if any answers were given.
package bankAccount;
public class CurrentAccount {
int account[];
int lastMove;
int startingBalance = 1000;
CurrentAccount() {
lastMove = 0;
account = new int[10];
}
public void deposit(int value) {
account[lastMove] = value;
lastMove++;
}
public void draw(int value) {
account[lastMove] = value;
lastMove++;
}
public int settlement() {
int result = 0;
for (int i=0; i<account.length; i++) {
result = result + account[i] + startingBalance;
System.out.println("Result = " + result);
}
return result;
}
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
}
}
At the moment, when I run the class, the expected System.out.println does not appear, and if I simply move public static void main(String[] args) to the top, this generates multiple red points. What is the best way for me to refactor my code so it works in the expected way?
you can have another class called Main in the file Main.java in which you can write your
public static void main(String args[])
and call
c.settlement();
in you main() to print.
Also one more advice,
in your constructor you have
account = new int[10];
which can hold only 10 ints.
in your deposit() and draw() you are not checking the account size. When the value of lastMove is more than 10 , the whole code blows up.
Hence I suggest you to use ArrayList
You never called the settlement method...
public static void main(String args[]) {
CurrentAccount c = new CurrentAccount();
c.deposit(10);
c.settlement();
}
I have the feeling that you come from some non-OOP language, like C or PHP. So some explanation:
The main method is static: that means it "exists" even when there is no object instance created, it can be thought of as if it belonged to the class instance.
on the contrary, for the other methods to "work", an instance is required.
This way the main method can be (and is actually) used as the entry point of the application
It is executed, and when it exists, (if no other threads are left running) the application terminates.
so nothing else is run that is outside of this method just by itself...
so if you don't call c.settlement(); - it won't happen...
Other notes:
Running main doesn't create an instance of the enclosing class
with new CurrentAccount(), you create an object instance, which has states it stores, and can be manipulated
be careful with arrays, they have to be taken care of, which tends to be inconvenient at times...
Why do you expect the printed output to appear? You don't actually call the settlement method, so that command is not executed.
You did not call settlement.. so nothing appears
if you add c.settlement... it is fine..
You have not called deposit() and settlement() in the main method untill you call, You cannot get expected output.
Hi I seem to have a problem calling a class in a main. Can somebody point it out?
KilometerTabel.java
package pratikum31d;
public static double mijlToKilometer() {
double mijl;
mijl = 0;
for (int i = 1; i < 11; i++) {
mijl = i;
}
double kilometer = 1.609 * mijl;
System.out.println(kilometer + " kilometer" + " dat is " + mijl + " mijl");
return kilometer;
}
Main.java
package pratikum31d;
public class Main {
public static void main(String[] args) {
kilometer = mijlToKilometer();
}
}
You never defined a variable called mijl in main. What value do you expect to get passed to mijlToKilometer?
===UPDATE ===
Your new code will have the following problems:
mijlToKilometer is still declared to expect an argument, so you won't be able to call it with no arguments. You must remove the double mijl from the definition of mijlToKilometer.
Your for loop doesn't do what you think it does, though I'm having a hard time identifying what it's supposed to do.
You must declare mijlToKilometer as public.
public static double mijlToKilometer(double mijl)
What are the packages for KilometerTabel and the main class? You haven't put any public/private/protected modifier before your static method. so by default, it will have default visibility. Which is visible within the package. make sure that you bave both classes in same package OR put a public keyword before methods.
secondly, can you please post exact exception?