Java class instance outside main method - java

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

Related

How Do I Access One Variable From Another Class?

I am not by my programming computer right now, so I can't post the code. I've been taking online lessons that I bought from Udemy so I'm still learning a lot.
I've looked at a decent number of posts, but the code they posts seem so long and complicated that it gets confusing. I have tried using a static variable, but the data needs to be changeable.
This is in android studios.
How do I access the data from one class in another class?
Class One:
//Class name is "ClassOne"
//Integer is an int named myNum and is equal to 1.
Class Two:
//Class name is "ClassTwo"
//I want my new int, myNewInt, to be equal to myNum.
If the field myNum is declared as public, you can access it by
any other class by typing the name of the object instance.myNu
If the filed myNum is declared as public static, you can access it
from any other class by typing the name of the class.myNum
If the field myNum is private, you need getters and setters, namely,
methods to access the file from an instance of the class that
contains it. Google them to get up to speed on why they're useful and
why you should use them.
Ex.
//public
ClassOne instance = new ClassOne();
ClassTwo instante2 = new ClassTwo();
instance2.myNewInt = instance.myNum;
//public static
ClassTwo instante2 = new ClassTwo();
instance2.myNewInt = ClassOne.myNum;
//getter
ClassOne instance = new ClassOne();
ClassTwo instante2 = new ClassTwo();
instance2.myNewInt = instance.getMyNum();
//and inside of ClassOne you'll have
private int MyNum = 5;
public getMyNum(){
return MyNum;
}
Note:
If the variable was only declared locally (inside the body of one of ClassOne's methods), you're gonna need to assign it to a filed, so that you can later access it from other classes.
Reading Material:
Getters and Setters
Access modifiers
You should create a getter method in the first class
public int getMyNum(){
return myNum;
}
In the second class you should have a setter method for the field myNewInt
public void setMyNewInt(int num){ this.myNewInt = num; }
And wherever you are running the code
myObject2.setMyNewInt(myObject1.getMyNum());
Sorry if there's any mistake, wrote this on the phone in a bus xD
There are couple of ways to do it.
Create an object of Class One and access fields via that object or create getter and setter methods.
Declare the field as static and access directly.

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().

Accessing instance methods that are two objects deep in Java

Say I have a class, Bobject with an instance variable and method to retrieve it:
public class Bobject {
private int bInstVar;
public Bobject() {
bInstVar = 1;
}
getBInstVar() {
return bInstVar;
}
}
If I create a class Cobject representing an object that is an array of Bobject like so:
public class Cobject {
public Bobject[] cInstVar;
public Cobject() {
cInstVar = new Bobject[2]; //arbitrary array size for simplicity of the question
for (i = 0; i <= 2; i++;) {
cInstVar[i] = new Bobject();
}
}
}
If I have a main program that creates a Cobject and attempts to access methods of the references to the Bobjects stored in each element, I find that I have to first access the Cobject instance variable, cInstVar. This means cInstVar has to be public for main() to get at it without a method if main is outside of the package or class.
My question is, is there a way around doing this:?
Cobject c = new Cobject;
c.cObject1[0].getBInstVar();
Instead, I want to have an object that is an array of another class and get to that classes instance methods easier like so:
Cobject c = new Cobject;
c.getBInstVar(); // error says 'array required, but Cobject found'
I'm still pretty new to Java (and stackExchange) so please forgive me if anything I've presented is unclear. Thanks in advance!
As a general rule of thumb class variable should be declared as private and you should use getter and settle methods....
Meaning you will need to create a getter method in 'Cobject' to get the 'Bobject' object your after.... Then another getter/setter method to access any attributes there, or a method to manipulate any data
But yes, you could hard code a method that will go into the array and return what you ask for. Probably need an index parameter tho
you can create a getter method for Bobject[] in Cobject class
and then you can do c.getCObject1()[0].getBInstVar();

Cannot use constructor variable after calling it with this()

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.

Why am I able to call private method?

I should not be able to invoke a private method of an instantiated object. I wonder why the code below works.
public class SimpleApp2 {
/**
* #param args
*/
private int var1;
public static void main(String[] args) {
SimpleApp2 s = new SimpleApp2();
s.method1(); // interesting?!
}
private void method1() {
System.out.println("this is method1");
this.method2(); // this is ok
SimpleApp2 s2 = new SimpleApp2();
s2.method2(); // interesting?!
System.out.println(s2.var1); // interesting?!
}
private void method2() {
this.var1 = 10;
System.out.println("this is method2");
}
}
I understand that a private method is accessible from within the class. But if a method inside a class instantiate an object of that same class, shouldn't the scope rules apply to that instantiated object?
Can static method like main access the non-static member of the class, as given in this example ?
Your main method is a method of SimpleApp, so it can call SimpleApp's private methods.
Just because it's a static method doesn't prevent it behaving like a method for the purposes of public, private etc. private only prevents methods of other classes from accessing SimpleApp's methods.
Because main is also a member of SimpleApp.
See below chart
Access Modifiers
**Same Class Same Package Subclass Other packages**
**public** Y Y Y Y
**protected** Y Y Y N
**no access modifier** Y Y N N
**private** Y N N N
As your method is inside car it's accessible based on above thumb rule.
From the Java Tutorial:
private modifier—the field is accessible only within its own class
The main method is inside the same class as the private method and thus has access to it.
private means "only stuff in this class can mess around with it". It doesn't mean "only this instance can call its methods", which seems to be what you're expecting. Any code in SimpleApp can use anything in any SimpleApp. The alternative would be to break encapsulation -- how would you make a proper equals method, for example, that didn't require access to another instance's fields, without making those fields protected or even public or requiring getters for data that should only be available inside the class?
The call you issue is from within the same class where your private method resides. This is allowed. This is the way 'private' is defined in java.
In the program, we created two instances of the class by using which we called two private methods. It's a kind of interesting to see this works is that this is the way we used to call public or default methods outside its class using object reference. In this case, it's all done inside the class definition, so it's valid. The same code put outside the class will result in error.
Because the private scope limits access to the class defining the method, and your main happens to be in the same class.
private modifier—the field is accessible only within its own class.
See Access Modifiers in the Java Documentation.

Categories

Resources