Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
Within my main method I'm trying to understand how to call up a variable from a different class.
I've attempted to break it down to the most simple solution possible just so I can get my head around the logic involved.
I have two classes within my package "var":
Class 1 - Source.java
package var;
public class Source {
int source1;
class setSource{
int source1 = 5;
}
}
Class 2 - Var.java
package var;
public class Var {
public static void main(String[] args) {
int Var;
Var = Source.setSource();
}
}
First time post here but I've spent 4 days and almost all my spare time trying to figure this out, please be gentle I'm dedicated but extremely newbie right now. Thanks in advance, I hope I've submitted this correctly.
Okay, I can sort of see what you were thinking but you've got some of the semantics incorrect. What you want to define is a method. A method takes the following structure:
<access modifier> <return type> <method name> (<method arguments>)
So for example
public void doSomething(String value) {
// This is the public method that returns nothing. It is called doSomething
// It expects a string value that it will call "value"
}
In your case, you want to create one of these, and you want to make a setter and a getter (or accessor and mutator if you're being posh).
Your Setter
This is just a normal method. Its purpose is to set the value of some class field. So let's define our class..
public class MyClass {
private int num;
}
Now we've got a class MyClass with a field num. But oh no, it's private, so let's create a setter so that the user can update the value.. Following our formula for methods, we start with a public access modifier. We then define the return type, which is void because it returns nothing. The name of the method should follow the java naming convention, which is the word "set" followed by the name of the member and finally the value for the setter.. Or all together:
public void setNum(int num) {
this.num = num;
}
This will update the value in the class with the value that you pass in. Excellent!
Your Getter
Well, this is nice and simple. Following our formula, it is a method that is public because everyone can access it; it returns something (in this case int) so that is the return type; the name follows the convention of "get" followed by the name and it expects no parameters.
public int getNum() {
return num;
}
This will return the value of num.
Finally, Using them!
public class MainClass {
public static void main(String[] args) {
MyClass myClass = new MyClass();
// Create a new MyClass instance.
myClass.setNum(4);
// Update the value in the class with the number 4.
System.out.println("The number is " + myClass.getNum());
// Outputs: "The number is 4"
}
}
you are using static calls, so you have to set this variables public static :
public static int source1;
and access them directly:
Var = Source.source1;
Your concepts are not well polished.
Your classes should have been like this
public class Source {
private int source;
public void setSource(int src){ // Called setter
source = src;
}
public int getSource(){ // Called getter
return source;
}
}
And
public class Var {
public static void main(String[] args) {
int Var;
Source source = new Source();
source.setSource(10);
Var = source.getSource(); // Var has value 10 in it.
}
}
Source is a class, you'll need to create an object that's a member of this class and then call the method on it. Additionally, the syntax for your method call is incorrect.
package var;
public class Source {
int source1 = 1;
public void setSource(){
source1 = 5;
}
}
Then:
package var;
public class Var {
public static void main(String[] args) {
Source source = new Source();
System.out.println(source.source1);
source.setSource();
System.out.println(source.source1);
}
}
I hope that makes sense to you when you compile it and run.
(Note that Java is case sensitive. On the above example, Source is the class and source is the object).
An alternative would be to declare methods and fields as static (static methods are called directly on the class), but I would suggest you make sure you understand the basic concepts of class and object instantiation before moving on to that.
Related
This question already has answers here:
When should I use "this" in a class?
(17 answers)
Closed 7 years ago.
I'm trying to get an understanding of what the the java keyword this actually does.
I've been reading Sun's documentation but I'm still fuzzy on what this actually does.
The this keyword is a reference to the current object.
class Foo
{
private int bar;
public Foo(int bar)
{
// the "this" keyword allows you to specify that
// you mean "this type" and reference the members
// of this type - in this instance it is allowing
// you to disambiguate between the private member
// "bar" and the parameter "bar" passed into the
// constructor
this.bar = bar;
}
}
Another way to think about it is that the this keyword is like a personal pronoun that you use to reference yourself. Other languages have different words for the same concept. VB uses Me and the Python convention (as Python does not use a keyword, simply an implicit parameter to each method) is to use self.
If you were to reference objects that are intrinsically yours you would say something like this:
My arm or my leg
Think of this as just a way for a type to say "my". So a psuedocode representation would look like this:
class Foo
{
private int bar;
public Foo(int bar)
{
my.bar = bar;
}
}
The keyword this can mean different things in different contexts, that's probably the source of your confusion.
It can be used as a object reference which refers to the instance the current method was called on: return this;
It can be used as a object reference which refers to the instance the current constructor is creating, e.g. to access hidden fields:
MyClass(String name)
{
this.name = name;
}
It can be used to invoke a different constructor of a a class from within a constructor:
MyClass()
{
this("default name");
}
It can be used to access enclosing instances from within a nested class:
public class MyClass
{
String name;
public class MyClass
{
String name;
public String getOuterName()
{
return MyClass.this.name;
}
}
}
"this" is a reference to the current object.
See details here
The keyword this is a reference to the current object. It's best explained with the following piece of code:
public class MyClass {
public void testingThis()
{
// You can access the stuff below by
// using this (although this is not mandatory)
System.out.println(this.myInt);
System.out.println(this.myStringMethod());
// Will print out:
// 100
// Hello World
}
int myInt = 100;
string myStringMethod()
{
return "Hello World";
}
}
It's not used a lot unless you have code standard at your place telling you to use the this keyword. There is one common use for it, and that's if you follow a code convention where you have parameter names that are the same as your class attributes:
public class ProperExample {
private int numberOfExamples;
public ProperExample(int numberOfExamples)
{
this.numberOfExamples = numberOfExamples;
}
}
One proper use of the this keyword is to chain constructors (making constructing object consistent throughout constructors):
public class Square {
public Square()
{
this(0, 0);
}
public Square(int x_and_y)
{
this(x_and_y, x_and_y);
}
public Square(int x, int y)
{
// finally do something with x and y
}
}
This keyword works the same way in e.g. C#.
An even better use of this
public class Blah implements Foo {
public Foo getFoo() {
return this;
}
}
It allows you to specifically "this" object in the current context. Another example:
public class Blah {
public void process(Foo foo) {
foo.setBar(this);
}
}
How else could you do these operations.
"this" keyword refers to current object due to which the method is under execution. It is also used to avoid ambiguity between local variable passed as a argument in a method and instance variable whenever instance variable and local variable has a same name.
Example ::
public class ThisDemo1
{
public static void main(String[] args)
{
A a1=new A(4,5);
}
}
class A
{
int num1;
int num2;
A(int num1)
{
this.num1=num1; //here "this" refers to instance variable num1.
//"this" avoids ambigutiy between local variable "num1" & instance variable "num1"
System.out.println("num1 :: "+(this.num1));
}
A(int num, int num2)
{
this(num); //here "this" calls 1 argument constructor within the same class.
this.num2=num2;
System.out.println("num2 :: "+(this.num2));
//Above line prints value of the instance variable num2.
}
}
The keyword 'this' refers to the current object's context. In many cases (as Andrew points out), you'll use an explicit this to make it clear that you're referring to the current object.
Also, from 'this and super':
*There are other uses for this. Sometimes, when you are writing an instance method, you need to pass the object that contains the method to a subroutine, as an actual parameter. In that case, you can use this as the actual parameter. For example, if you wanted to print out a string representation of the object, you could say "System.out.println(this);". Or you could assign the value of this to another variable in an assignment statement.
In fact, you can do anything with this that you could do with any other variable, except change its value.*
That site also refers to the related concept of 'super', which may prove to be helpful in understanding how these work with inheritance.
It's a reference of actual instance of a class inside a method of the same class.
coding
public class A{
int attr=10;
public int calc(){
return this.getA()+10;
}
/**
*get and set
**/
}//end class A
In calc() body, the software runs a method inside the object allocated currently.
How it's possible that the behaviour of the object can see itself? With the this keyword, exactly.
Really, the this keyword not requires a obligatory use (as super) because the JVM knows where call a method in the memory area, but in my opinion this make the code more readeable.
It can be also a way to access information on the current context.
For example:
public class OuterClass
{
public static void main(String[] args)
{
OuterClass oc = new OuterClass();
}
OuterClass()
{
InnerClass ic = new InnerClass(this);
}
class InnerClass
{
InnerClass(OuterClass oc)
{
System.out.println("Enclosing class: " + oc + " / " + oc.getClass());
System.out.println("This class: " + this + " / " + this.getClass());
System.out.println("Parent of this class: " + this.getClass().getEnclosingClass());
System.out.println("Other way to parent: " + OuterClass.this);
}
}
}
Think of it in terms of english, "this object" is the object you currently have.
WindowMaker foo = new WindowMaker(this);
For example, you are currently inside a class that extends from the JFrame and you want to pass a reference to the WindowMaker object for the JFrame so it can interact with the JFrame. You can pass a reference to the JFrame, by passing its reference to the object which is called "this".
Every object can access a reference to itself with keyword this (sometimes called the this
reference).
First lets take a look on code
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
return this.name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
}
In the above method getName() return instance variable name.
Now lets take another look of similar code is
public class Employee {
private int empId;
private String name;
public int getEmpId() {
return this.empId;
}
public String getName() {
String name="Yasir Shabbir";
return name;
}
public void setEmpId(int empId) {
this.empId = empId;
}
public void setName(String name) {
this.name = name;
}
public static void main(String []args){
Employee e=new Employee();
e.setName("Programmer of UOS");
System.out.println(e.getName());
}
}
Output
Yasir Shabbir
this operator always work with instance variable(Belong to Object)
not any class variable(Belong to Class)
this always refer to class non static attribute not any other parameter or local variable.
this always use in non static method
this operator cannot work on static variable(Class variable)
**NOTE:**It’s often a logic error when a method contains a parameter or local variable that has the
same name as a field of the class. In this case, use reference this if you wish to access the
field of the class—otherwise, the method parameter or local variable will be referenced.
What 'this' does is very simply. It holds the reference of current
object.
This keyword holds the reference of instance of current class
This keyword can not be used inside static function or static blocks
This keyword can be used to access shadowed variable of instance
This keyword can be used to pass current object as parameter in function calls
This keyword can be used to create constructor chain
Source: http://javaandme.com/core-java/this-word
This question already has answers here:
Static Classes In Java
(14 answers)
Closed 3 years ago.
So, in short. I have two classes.
package rpg;
public class Engine {
public void main(String args[]) {
Start.gameStart();
System.out.println(menuResult);
}
}
and
package rpg;
public class Start {
int menuResult = 3;
public int gameStart()
{
return menuResult;
}
public int getMenuResult()
{
return Start.menuResult;
}
}
It keeps throwing up the error 'Cannot make static reference to non-static method gameStart()'.
I'm sure I'm missing something simple, but can't find it.
Thanks!
You need to create instance of Start class and call gameStart() method on that instance because gameStart() is instance method not static method.
public void main(String args[]) {
new Start().gameStart();
..................
}
Only static methods can be accessed by using class name as perfix.
public int gameStart() <--- Instance method not static method
call it on instance
Start start = new Start();
start.gameStart();
So finally your classes should look like below
public static void main(String args[]) {
Start start = new Start();
start.gameStart();
System.out.println(start.getMenuResult());
}
public class Start {
private int menuResult = 3;
public int gameStart() {
return this.menuResult;//Don't know why there are two methods
}
public int getMenuResult() {
return this.menuResult;
}
}
first of all the main method should be
public static void main(String args[]) {
}
I assume you can have multiple games, and hence you should be able to start multiple instances so you should create a non static class that can be created and then actions performed against.
to answer your original question, you need to have a static variable that have static getters and setters..
public class Start {
private static int menuResult = 3;
public static int gameStart()
{
return menuResult;
}
public static int getMenuResult()
{
return Start.menuResult;
}
If you need the method to be static, just add the keyword static in the function definition. That would get rid of the error. But if you want to keep the class Start the way it is, then you should create an instance of Start in the main function and then call the method. Hope that helps!
you are trying to invoke a method on its class name. you should be creating a new object and invoke its method
public void main(String args[]) {
new Start().gameStart();
System.out.println(menuResult);
}
Start.gameStart() refers to a method which would be public static int gameStart() because Start is the class and not an instance of the object.
If you declare a method on an object, you need to apply it to instance of the object and not its class.
When to use static or instanciated methods ?
instanciated : whenever you need to apply the method to the object you're in. example : mycake.cook();
static : when the actions you do inside your method have nothing to do with an object in particular. example : Cake.throwThemAll();
mycake is an instance of a Cake, declared this way : Cake mycake = new Cake();
Cake is the class representing the object.
You should, i guess, have a read at some object oriented programmation course if you still have a doubt about objects, classes and instances.
While Other answers are Correct , that remains the Question that Why you Can't access Instance
method Directly from Class name , In Java all static (methods , fields) bind with Class Name and when Class Is Loading to the Memory (Stack) all static members are Loading to the Stack , and this time Instance Method is not visible to Class. instance Method will Load into Heap portion in the memory and can only be access by Object references .
Executed Python code:
class Test(object):
item = 0
def __init__(self):
print(self.item)
def test(self):
print(self.item)
class Subclass(Test):
item = 1
s = Subclass()
s.test()
gives:
1
1
Executed analogical Java code:
public class Test {
int item = 0;
Test(){
System.out.println(this.item);
}
void test(){
System.out.println(this.item);
}
public static void main(String[] args){
Subclass s = new Subclass();
s.test();
}
}
class Subclass extends Test {
int item = 1;
}
gives:
0
0
Apparently, Java method inherited from base class (Test) uses also base class' member variables. Python method uses the member variable of derived class (Subclass).
The question: Is there any way to achieve the same or at least similar behaviour in Java like in Python?
Objects in Python are pretty much just like Dictionaries in Python. You can think of each instance of Test and Subclass as a Dictionary that is updated by the __init__ code and assignments in the body of the class you declare. You can picture the code you wrote working something like this:
class Test(object):
item = 0 # self['item'] = 0
def __init__(self):
print(self.item) # print(self['item'])
def test(self):
print(self.item) # print(self['item'])
class Subclass(Test):
item = 1 # self['item'] = 1
s = Subclass() # Test.__init__({})
s.test()
Python uses duck-typing, so item is just some property of whatever you happen to have an instance of. Notice that you don't ever actually have to declare item—you just assign a value. This is why you're able to "override" the value in the sub-class—because you're actually just overwriting the old value of the same field. So in the example you gave, the item in Subclass isn't actually overriding the item in Test; rather, they are the same field in a Python object instance.
In Java fields actually belong to specific classes. Notice how in your code you actually have two declarations of the field int item: one in Test and one in Subclass. When you re-declare the int item in Subclass you are actually shadowing the original field. See Java in a Nutshell: 3.4.5. Shadowing Superclass Fields for more info.
I'm not sure exactly what you're trying to do with your example, but this is a more idiomatic Java approach:
public class Test {
private int item;
public Test() {
this(0); // Default to 0
}
public Test(int item) {
setItem(item);
test();
}
public void test() {
System.out.println(getItem());
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.test();
}
public void setItem(int item) {
this.item = item;
}
public int getItem() {
return item;
}
}
class Subclass extends Test {
public Subclass() {
super(1); // Default to 1
}
}
Notice how the value of item is set via a constructor argument rather than by simple assignment. Also notice how item is private and that there is now a getter and setter method to access it. This is more Java-style encapsulation.
That seems like a lot of code, but a good IDE (such as Eclipse or IntelliJ) will auto-generate a lot of it for you. I still think it's a lot of boiler-plate though, which is why I prefer Scala—but that's a whole different discussion.
Edit:
My post grew so long that I lost track of why I wanted to introduce getters and setters. The point is that by encapsulating access to the field you're able to do something more like what you had in Python:
public class Test {
// Same as above . . .
}
class Subclass extends Test {
private int subclassItem = 1;
public int getItem() {
return subclassItem;
}
public void setItem(int item) {
this.subclassItem = item;
}
}
Now the item field has effectively been overridden since all access to it is done through the getter and setter, and those have been overridden to point at the new field. However, this still results in 0 1 in the output rather than the 1 1 you were expecting.
This odd behavior stems from the fact that you're printing from within the constructor—meaning the object hasn't actually been fully initialized yet. This is especially dangerous if a this reference is passed outside the constructor during construction because it can result in outside code accessing an incomplete object.
You could overload the superclass constructor to initialise the field item in Test to 0:
public class Test {
int item = 0;
Test(){
System.out.println(this.item);
}
Test(int item) {
this.item = item;
System.out.println(this.item);
}
void test(){
System.out.println(this.item);
}
public static void main(String[] args){
Subclass s = new Subclass();
s.test();
}
}
class Subclass extends Test {
public Subclass() {
super(1);
}
}
Use an initializer instead of redeclaring the fields:
public class Test {
int item = 0;
...
}
public class Subclass extends Test {
{
item = 1;
}
}
Note: depending on your package structure, you might want to declare item as protected.
I've got this int variable inside the class StringSplit whose value I need to pass to another class called EndStatement to print out; can't really pass it as a parameter though I think. How can I best get the variable to where I need it? Can someone help with a hint? I've read the Java tutorials but don't quite get them. Variables and passing them around seem to be one of my Achilles' heels in Java programming.
EDIT TO ADD: parseCommands can call several different Statement classes e.g. EndStatement or PrintlnStatement depending on the first element of an Array parsed from a String which serves as a keyword to a HashMap called commandHash. The Statement classes implement the Directive interface which only has a method called execute with the parameterString[] parts. (EndStatement implements Directive). Expanded the parseCommands method to show what's going on.
public class StringSplit
{
public void parseCommands(String fileName)
{
//FileReader and BufferedReader to read a file with the code
//to execute line by line into an ArrayList myString
int lineCounter=0; //need to get this variable's value into class EndStatement
for (String listString: myString)
{
lineCounter++;
String[] parts=listString.trim.split("[\\s]+", 2)//split String into 2 parts
//to get commands
Directive directive= commandHash.get(parts[0])//parts[0] is the hashmap keyword
}
public class EndStatement implements Directive
{
public void execute(String[] parts)
{
//need to get lineCounter here--how?
System.out.print(lineCounter +"lines processed.");
}
public static void main (String[]args)
StringSplit ss = new StringSplit();
ss.parseCommands(args[0]);
}
This is my first time answering a question but I think I'm right.
In StringSplit you want to declare linceCounter in a data field.
public class StringSplit
{
public void parseCommands(String fileName)
{
lineCounter=0; //this is the variable I need to pass into a different class
for (String listString: myString)
{
lineCounter++;
//more code here
}
}
public int getLineCounter()
{
return lineCounter;
}
private int lineCounter; //this is what I call a data field, you should declare these as private as oppose to public to comply with encapsulation
}
Then in your main method call getLinceCounter, then pass what it returns to EndStatment.
Does this make sense? Did I understand your question right?
public class StringSplit
{
private int lineCounter=0;
public void parseCommands(String fileName)
{
for (String listString: myString)
{
lineCounter++;
//more code here
}
}
public int getLineCounter() {
return lineCounter;
}
}
public class EndStatement implements Directive
{
StringSplit ss = new StringSplit();
public void execute(String[] parts)
{
//need to get lineCounter here--how?
System.out.print(ss.getLineCounter() +"lines processed.");
}
public static void main (String[]args)
{
ss.parseCommands(args[0]);
}
}
I think you mix some terms. There is no such thing as passing variables from one class to another. I assume that what you want to do is simply be able to access (set/get) your variable outside StringSplit class. In order to do that you must declare lineCounter outside parseCommands method as StringSplit's property. Currently lineCounter is local to parseCommands method and as such cannot be visible/accessed outside that method not mentioning to be able to access it from outside a class/object. Do that:
public class StringSplit
{
public int lineCounter = 0;
...
Now you'll be able to access lineCounter from different methods of the same class and from methods outside your class. Making lineCounter public gives others full access to it. As 'Jon' has pointed out it may be dangerous sometimes but for this example case is acceptable. You may see how writing from outside can be prevented using 'Nurlan's' private field with member used to provide read acces only.
Right now I have two .java files.
The Main.java:
public class Main {
static int integer = 15;
NeedInteger need = new NeedInteger();
}
and the NeedInteger.java
public class NeedInteger {
System.out.println(integer);
}
This is of course very simplified, but is there any way I can accomplish this?
As many have answered, the correct method is to pass the value in to the constructor of the new class.
If for some reason you cannot do that, then you can use a public static accessor method in Main to access the value (this would be slightly better than just making the field public).
E.g.
public class Main
{
private static int integer = 15;
public static int getInteger()
{
return integer;
}
}
public class NeedInteger
{
public NeedInteger()
{
int integer = Main.getInteger();
}
}
Add a constructor to NeedInteger (and optionally a member if you need to also store it):
public class NeedInteger {
private int integer;
public NeedInteger(int integer) {
this.integer = integer;
System.out.println(integer);
}
}
Then pass your value when you create the instance:
public class Main {
static int integer = 15;
NeedInteger need = new NeedInteger(integer);
}
You would have to do some bad juju moves (like using a global variable) or pass it to the constructor.
NOTE: your
public class NeedInteger {
System.out.println(integer);
}
has no method in it. I would recommend all this to be rewritten as such:
public Class NeedInteger {
NeedInteger(int integer) {
System.out.println(integer);
}
}
If you really want the work to be done on construction.
EDIT: From your comment above.
Instead, have the class structured so:
public Class NeedStringArray {
NeedStringArray(String[][][] stringArr) {
//work with String array here
}
}
That has no real additional overhead, since the actual array will not be passed, but only a reference to it. You WILL likely want to set the array to be final or something, to avoid it being edited in the NeedStringArray constructors.
integer is private, so it cannot be accessed by NeedInteger. you'll have to make it public or use a setter or getter and you'll need to use Main.integer since it's static.
Generally, you set in the Constructor.
Pass in the variable to the class constructor.
An array reference would be just that--a reference.
Or you could pass in the class itself, or use a static (meh).
Per your comment I'd say you can either host your array in a singleton
or as others suggested have the second class accept the reference to the array in the constructor. You can then use Dependency Injection framework (e.g. Guice) to get wire them up