Cannot use constructor variable after calling it with this() - java

I made a program for the sole purpose of testing out constructors.
In the constructor Car(), I declare int hello = 5. But when I call that constructor with this(), I still cannot use hello (it cannot be resolved to a variable, AND eclipse complains that hello is never used). I thought that calling this() would run the code in Car(), therefore extending the scope of hello. What is wrong?
class Car {
public Car(){
int hello = 5;
}
public Car(int howmany){
this();
howmany+=hello;
}
}
I thought that calling this() would run the code in Car(), thus extending the scope of hello to within the Car(int howmany) constructor?
I am new to Java so there may be something elementary I don't know.

hello is declared inside the constructor, so it has a scope only inside the constructor. I dont know what are you trying to do but maybe you need to declare hello as an attribute of Car.

Try
class Car {
int hello;
int howMany;
public Car(){
hello = 5;
}
public Car(int howmany){
this();
this.howMany = howmany + hello;
}
}
This declares hello and howMany variables as instance variables and now they will be available to all class methods and constructors.

Currently, the variable 'hello' can only be called from inside the constructor. A variable can only be called from the same part of the code it was declared within; if it is within a method it will only be accessible through that method.
If you would like to make this variable accessible from all methods within that class, declare 'hello' before the constructor methods and add the word 'private' in front of it. If you want all classes to be able to access it, add 'public' in front of it. Here is an example of both:
class Car {
private int hello; //Accessible from within only the class
public int hello; //Accessible from other classes
public Car(){
int hello = 5;
}
public Car(int howmany){
this();
howmany+=hello;
}
}
I hope this helped. Just remember that where you declare a variable matters, as do the tags in front of it. And keep in mind not to declare two version of the hello variable like I did up there, that was just an example.

Related

How to call an entire class from another class in Java?

I am a beginner in Java. I have two packages in my current project. Each of the packages have two classes called the "packageClassOne" and "packageClassTwo".
The packageClassTwo has a constructor and other public methods.
I want to call the PackageClassTwo from an if statment located in the PackageClassOne. My code looks something like this
packageClassOne:
public class packageClassOne {
public void selectComponent(boolen) {
if(/* check condition*) {
packageClassTwo value = new packageClassTwo();
}
}
}
packageClassTwo:
public class packageClassTwo {
public packageClassTwo(String name){ //Constructor
int length = name.length();
}
public String CreateWord(){
/*functionality ofthis method*/
}
public String CreateSentence(){
/*functionality ofthis method*/
}
}
The problem is that everytime I call the packageClassTwo from my packageClassOne it tries to call the constructor instead of calling the class itself. I want to call the entire packageClassTwo instead of just the constructor.
Can somebody help me please? Thank you in advance for your help
Since Java is an object oriented language, you have to have a mindset of dealing with instances that are realizations of the classes you defined. These are the objects.
So if you want to call a method from packageClassTwo class, you first create an object of packageClassTwo. You seem to be trying to do just this. Once you have the object, you can call its methods. For example
//Instantiate an object by calling the constructor
packageClassTwo object = new packageClassTwo(string);
//Now call its methods
String val = object.CreateWord()
There is no such thing as "calling a class". You call methods of objects of a class.
Occasionally, there might be a well founded need to call methods of a class without initializing objects. Look into static methods and classes for further reading.
If you want to call all methods of packageClassTwo you have to do it explicitly
packageClassTwo pct = new packageClassTwo("");
pct.CreateWord();
pct.CreateSentence();
If you allways want the 2 methods to be called when you create a new packageClassTwo object, than you can just add the calls to the constructor
public packageClassTwo(String name) {
int length = name.length();
pct.CreateWord();
pct.CreateSentence();
}
Edit:
Note that in the second case, if you end up only calling the 2 methods from inside the constructor, it is better to make them private.
As a sidenote, it is a general convention in java to have class names start with a upper case letter : PackageClassTwo not packageClassTwo, and method names to start with lower case createWord not CreateWord. This wll make your code more readable.
If you want to call all the methods from the packageClassTwo, call them from the packageClassTwo constructor
public packageClassTwo(String name)
{
int length = name.length();
CreateWorld();
CreateSentence();
}
I don't think your code will run without compiling errors.because you did not declare the constructor packageClassTwo().

Java class instance outside main method

I am studying Java, and I am a beginner.
I tried to create three classes (in the same package).
One with main method (JavaApp1), another that I've called "JavaClass1" and the last class "JavaClass2".
Here's the JavaClass1's code:
public class JavaClass1 {
public int var1;
public int var2;
}
JavaClass2's code:
public class JavaClass2 {
JavaClass1 ogg = new JavaClass1();
ogg.var1 = 4;
ogg.var2 = 7;
}
In the JavaClass2, Netbeans show me two error, related to the assignments (JavaClass1.var1 and JavaClass.var2) "Package ogg does not exist. expected.
But if i Create the Class instance and attributes assignments inside the main method, there are no problems. Why?
You cannot set the field of an object outside a method.
ogg.var1 = 4;
ogg.var2 = 7;
has to be inside some method.
Classes consist of class fields (like your var1 in the first class) and methods. Methods "do the work", i.e. execute code. You can initialize fields, but all other code has to be inside a method.
One more note: It is very bad style to have public fields. Please write getters and setters instead.
Try using getter and setters,
read this
http://www.tutorialspoint.com/java/java_encapsulation.htm

How to use a Get method in java

A ton of questions have been asked on how to create getter and setter methods in java. But i have yet to see one that actually tells me how to use it.
Say i have Private int i = 1; in class A and i want to access it in class B.
I would first create a get method in class A called getIntI(); which would return the value of i.
Then in class B if i wanted to create an if statement that would need the value of i how would I get int i's value. The following is my try and calling the get method which does not work.
if(getIntI == 1)
{System.out.print.ln("int i is one");}
It is probably a really stupid question but i cant find an answer for it elsewhere.
In class A:
public int getIntI(){
return i;
}
Note: Now since your variable is single character named (just I), getter method is named getIntI since the name getI makes lesser sense. But generally, getter methods are something like get+VariableName and do not involve mentioning type. For example if I had a variable called int count, my method would be named getCount instead of getIntCount. Thats the general convention.
Also, naming variables in single char formats (like x, y etc) is discouraged because it may create confusion and management difficulty in complex programs. Though in very small programs they are fine.
Moving back to topic, if you want to access method getIntI() in class B, you will either have to inherit class A or create an object of class A reference to its method.
For class B:
Creating object
A obj = new A();
if(obj.getIntI() == 1)
// Do stuff
Inheriting class A:
public class B extends A{
... // Your stuff
if(getIntI() == 1)
// Do stuff
... // Your stuff
}
Of course there are other ways but these are simpler ones.
if class B extends class A then do only this changes,
if(getIntI() == 1)
If above inheritance was not there then do this,
if(new A().getIntI() == 1)
The problem is that you need to create a object derived from class A before you can access its variables/methods using
A a = new A();
where "a" is the name of the object. Then you can access the getter method by calling a.getIntI. You can also declare the int variable as static so that you wouldn't have to instantiate any objects. An example of class A with the static variable and getter method would be:
public class A {
private static int i = 1;
public static int getIntI() {
return i;
}
}
With this, you can call the getter method with A.getIntI().
First, if you want to access one of A's non-static methods (in this case, getIntI), you need an instance of A, or you can just declare it static.
Secondly, A method call needs a parameter list, even an empty one is needed. getIntI does not need any parameters, so you should add () at the end.
Now, you can get an instance of A somewhere and call it aObj. Andd then you can use it in the if statement:
if (aObj.getIntI == 1)
And remember to add ()!
if (aObj.getIntI() == 1)
Alternatively, you can declare i in A as static. There are two main differences between a static and a non-static variable.
You don't need an instance of the declaring class to access the static variable.
Unlike non-static variables, there is only one static variable. If you have a non-static variable i, you can create lots of instances of A and each instance will have its own i
Now let's see this in action, declare i as static:
public class A {
private static int i = 1;
public static int getIntI () { return i; }
}
Note how both i and getIntI are declared static.
Then you can use in a if statement like this:
if (A.getIntI() == 1)
Note how I use the class name A to access the method, not an instance of A.

No parentheses in java

I am learning Java and I have learned that methods use parentheses for passing parameters. However, I have also noticed that sometimes I see code which to me looks like a method but it does not have parentheses.
MyObject.something()
MyObject.somethingElse
Where somethingElse does not have parentheses. I assume this is similar to how an arrayList has the size method for getting its size:
myList.size()
whereas an array has length to get its size, which does not have parentheses:
myArray.length
Is my assumption correct? If not, what is the difference?
This is probably an elementary question, but because of the amount of words I need to explain this problem, I have had trouble searching for it.
somethingElse is a property (data member), not a method. No code in the class is run when you access that member, unlike with a method where code in the class is run.
Here's an example:
public class Foo {
public int bar;
public Foo() {
this.bar = 42;
}
public int getBlarg() {
// code here runs when you call this method
return 67;
}
}
If you create a Foo object:
Foo f = new Foo();
...you can access the property bar without parens:
System.out.println(f.bar); // "42"
...and you can call the method getBlarg using parens:
System.out.println(f.getBlarg()); // "67"
When you call getBlarg, the code in the getBlarg method runs. This is fundamentally different from accessing the data member foo.
it is a class field which isn't a private field (usually it can be protected,package or public), so you can take it straight from your class. Usually fields are private, so you cannot take it like this outside your class definition.
myList.size() call a method defined in list class (public defined)
myArray.length call a property in array class not method
public class MyClass{
public int length;
public int size(){
....
}
}
MyClass mc =new MyClass();
mc.length;
mc.size();
This is triggering method called something of the instantiated object called someObject.
someObject.something();
This is accessing a property of the object called someObject (property which is public, most probably).
someObject.name

Accesing a method from another class file?

I need to acces a variable (an int) from another class file. How would I do this? It's a public int, I need to get the int value and put it into a file.
If you have an instance:
AnotherClass another = new AnotherClass();
Then if the field (instance variable) is public:
another.someField;
or if you have a getter method
another.getSomeField();
If none of these is true - add a getter method (this is the preferred way to access instance variables).
If you can't change the class - as a last resort you can use reflection.
Example:
MyClass myclass = new MyClass();
System.out.print(myclass.myint)
Best practice code states that if the variable is not a Static Final, then you should create getters & setters inside the class:
public class Main{
int variableName;
public int getVariableName(){
return this.variableName;
}
public setVariableName(int variableName){
this.variableName = variableName;
}
}
If you want to acess it from another class file then you have to instantiate an Object and then access it using the public method:
Main m = new Main();
int a = m.getVariableName();
Hope it helps.
If you have an instance of that other class, you access it as {instance}.varable.
That varaiable need to either be public, or it needs to be in the same package and not private, or it must be a protected variable in a superclass.
If the variable is static, then you don't need an instance of that class, you would access it like {ClassName}.variable.
Far and away the best thing to do here would be to make the int you need to access a Property of the other class and then access it with a 'getter' method.
Basically, in the other class, do this:
public int Number
{
get
{
return number;
}
set
{
number = value;
}
}
private int number;
Doing this allows you to easily set that in to something else if you need to or to get it's current value. To do this, create an instance of the "AnotherClass" as Bozho already explained.

Categories

Resources