Create objects and add instances to them (Java) - java

I'm trying to create an object (LineItem), and then create variables of that object. I want to create a 'cookie' that has a price, a name, and a quantity assigned to it. My problem begins at cookie.price = 5, my IDE tells me that 'package cookie does not exist.' I am very confused. It gives me the same error whether or not I declare cookie outside of the LineItem class.
public static void main(){
public class LineItem{
int price;
String foodName;
int quantity;
LineItem cookie = new LineItem();
cookie.price = 5;
}
}

In Java, you cannot directly write the executable statements in class.Only variables declaration is allowed outside the method/blocks/constructor
You need to move the code cookie.price = 5; into a method/constructor/block.

Put it into a method. You have not got a main method and your program cant start this way. No research done. Use proper syntax and learn the basics. To refer to the class use the this keyword. You shall not create an instance of the class again in the same class. Instead of using this.variable you can refer to the variable straightforward if it is in the same class declared outside of any methods

Related

Using of #Field variable in Groovy script

I have a script with a global variable in my Groovy script
I have a problem using it inside a function. May I know the reason or the right way?
I'm gonna be using it for a logger. Other primitive data types can be accessed but this, I can't.
#Field def log = Logger.getLogger("NameOfLogger")
log.info("TEST")
testFunction()
private void testFunction() {
//cannot use the log variable here
}
I know now the cause. It's because I was declaring it as def
But I still don't know the real reason why def can't be used.
The following code works for me (I haven't tried with log but used online groovy console):
import groovy.transform.Field
import groovy.transform.Canonical
#Canonical
class Person {
String name
int age
}
#Field person = new Person("John", 30)
println "Global $person"
testFunction()
private void testFunction() {
println "Inside method: $person"
}​
Output:
Global Person(John, 30)
Inside method: Person(John, 30)
So make sure you have proper imports first of all
Now, it worth mentioning that groovy creates an implicit class and Field annotation alters the scope of the global variable and moves it to be a field of that implicit class so that both person and testFunction will both belong to this class and there won't be a problem to access the field from within the method.

How these codes work (Constructor And ListView)

I was following the udemy android app development course, In the course, we were writing code to Create A listview and get some data when the user clicks on the list, to do that the teacher uses a thing called Constructor I know how constructors work theoretically but can't understand the way it works in code. It will be great if someone can explain what these lines of codes do.
edit: Full Code is here https://github.com/atilsamancioglu/A14-LandmarkBook
import android.graphics.Bitmap;
public class Globals {
private static Globals instance;
private Bitmap chosenImage;
private Globals(){
}
public void setData(Bitmap chosenImage){
this.chosenImage=chosenImage;
}
public Bitmap getData(){
return this.chosenImage;
}
public static Globals getInstance() {
if(instance==null){
instance = new Globals();
}
return instance;
}
}
Constructors are special methods invoked when an object is created and are used to initialize them.
A constructor can be used to provide initial values for object attributes.
You can think of constructors as methods that will set up your class by default, so you don’t need to repeat the same code every time.
In your codes, you can define the constructor as below(it may be unrelated, it's just an example):
private Globals(int id){
return chosenImage.setId(id);
}
The constructor is called when you create an object using the new keyword:
Globals objectGlobe = new Globals(000008);
Also a single class can have multiple constructors with different numbers of parameters.
The setter methods inside the constructors can be used to set the attribute values.
It's not bad to be mentioned that; Java automatically provides a default constructor, so all classes have a constructor, whether one is specifically defined or not.

Does ReflectionTestUtils works only on fields of a class, not on variables defined inside a method of that class?

Does ReflectionTestUtils works only on fields of a class, not on variables defined inside a method of that class?
I tried to test the fields of a class, it works perfectly fine using ReflectionTestUtils, if I try it on variables of a method, I get an IllegalArgumentException.
Example Code:
public class Check {
String city;
public void method() {
city = "Bangalore";
String Street = "MGRoad";
}
}
If I want to have a JUnit tests for the above class using ReflectionTestUtils.
Check c = new Check();
assert ReflectionTestUtils.getField(c, "city").equals("Bangalore")
-> works fine.
assert ReflectionTestUtils.getField(c, "Street").equals("MGRoad")
-> gives illegalArgumentException.
Please have a look and suggest me if I can test the attributes of a method.
You cannot access local variables using reflection and String Street = "MGRoad"; is local variable to that method
If what you mean is variables local to methods/constructors, you can not access them with reflection. ... There is no way to obtain this information via reflection. Reflection works on method level, while local variables are on code block level.

Trying to access public objects in other package

Hi I am trying to access a public object in another package within a project.
I am trying to access the 'opponent' object which is of type 'Character' in the Attribute class.
public class Engine {
public static Character opponent;
}
Class I am trying to access object in. "This class is in another package".
public int opponentAttackDamage() {
int attack = opponent.getAttribute().getAttack();
}
In order to access an static attribute from anywhere even in the same class where it's declared (as a good practice) you should use the name of the class follow by dot an the name of the attribute:
Engine.opponent.getAttribute().getAttack();
Also you should have in mind that opponent object must be initialized in somewhere in your class (opponent = new Opponent() - I guess - ).
If opponent is a static attribute of the Engine class, and the method you are accessing it from is not in the same class, you need to mention Engine.opponent to access it. Also, you need to import the package where Engine class is defined.

Private variables in a class can be accessed from main in Java?

I've recently started learning Java using JDK1.6. If this is a silly question, please excuse me.
If private variables can be directly accessed by objects in main() how are they 'private'?
public class Account1
{
private int accountNum;
private String name;
Account1() {
accountNum = 1101;
name = "Scott";
}
public void showData() {
System.out.println("Account Number: " + accountNum +
"\nName: " + name);
}
public static void main(String[] args) {
Account1 myA1 = new Account1();
myA1.showData();
System.out.println(myA1.accountNum); //Works! What about "Private"?!
}
}
Which gives the output:
Account Number: 1101
Name: Scott
1101
Your main is in the Account1 class, so it's still in the same scope.
Private variables can be accessed from any code belonging to the same type. If your main method was in a separate class then it wouldn't be able to access them (without using reflection).
The "main" method of a given class is part of that class. Methods that are part of a class have access to private members of that class. That makes sense to me. Doesn't necessarily mean you should use it, of course.
One way to think about it is to think about one class's knowledge of another class's internal workings. My Person class shouldn't know what happens inside my Order class; it just calls public methods on it. But anything inside Person will of course know about the internal structure of Person -- even a different instance of Person.
This is because the main() function is a member of the class. It has access to all members of the class.
In real world code, the main function is usually situated in a "harness" class that actually bootstraps the rest of the code. This harness class is usually very lightweight and instantiates other classes that do the real work.
They are private in that they can only be accessed by that class. This means they are accessible from static methods of that class (such as main) and also from instance methods (such as showData).
One instance of the class can also access private members of another instance of the class.
If you had a separate class, say, Account2, it would not be able to access provate members of Account1.

Categories

Resources