Trying to access public objects in other package - java

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.

Related

Accessing variables of the wrapper object in OOP

I am creating an application in VBA for my employer (and a similar one in Java for hobby purposes) and its purpose is to 'contain' different tools that will help in our daily work. It's going to be some kind of platform with the main app window and from there a user can access some of the application components like for instance a sub-program when a user can give me feedback on application's functionality, then the info will be stored in a database that I can access later.
I already have a structure: an Application class, that contains the Application Manager and this one class contain an array of fields of the SubApp type. A SubApp type contains view, logic, and business of a sub-application. The Application class also contains members like the name of the app and the information about the user that is currently using the app (previously accessed from the application database).
Whenever a sub-app launch, I would like to put on the title bar the name of the app as well as the name of the sub-app, something like application_name - sub_app_name. The problem is, that I have no idea how can I access it the 'right way'. Recently I've achieved this by creating the app variable as a global object, then accessing it is no problem using some getters. I feel however that storing an application variable as a global variable is a bad practice.
The same problem occurs with the member variable storing info about the current user. I'd like to store the information about the current user while he's giving feedback (tool for giving a feedback is a sub-app in my application)
So here is my question: how can I access the methods/variables of a wrapping object from within one of the member methods/variables?
Any suggestions regarding the overall design of the application would also be welcome.
Object oriented design: use getters and setters for all fields is proper practice. If you want to be lazy, make all your fields public and they will be accessible from the object without getters or setters.
If you wish to access a variable throughout multiple methods in a class.
A) You'll can make a variable global
B) Create a local variable, and pass it as a parameter until you no longer need to use it.
public class Main { //All implementations stated above
private Object globalObject;
public static void main(String[] args) {
Object localObject;
method1(localObject);
method2ThatUsesGlobalObject();
}
}
Accessing variables between classes:
A) Make a variable static
B) Pass it through method parameters, or constructor parameters
C) Use abstract classes or interfaces
Here are examples of the code usage I've stated
public abstract class JavaAbstractClass {
public abstract Object giveMeThisObjectWhenINeedItThanks();
}
public interface JavaInterface {
Object giveMeThisObjectWhenINeedItThanks();
}
public class Main { //All implementations stated above
public static Object object; //Accessible by Main.object everywhere
public static void main(String[] args) {
Object local;
ClassOne class = new ClassOne();
class.method1(local);
new ClassWithInterface() {
#Override
public Object giveMeThisObjectWhenINeedItThanks() {
return local;
}
};
new JavaAbstractClass() {
#Override
public Object giveMeThisObjectWhenINeedItThanks() {
return local;
}
};
}
}

Java class declaration - having a '.' and static classes

Hi I was looking at this syntax from the Android API and found it a bit weird.
java.lang.Object
↳ android.graphics.BitmapFactory.Options
public static class
BitmapFactory.Options
I have never seen a class with a '.' in the middle of it. Why didn't they just call the class 'BitmapFactoryOptions'?
Then I was confused even more because I saw this code in a book
final BitmapFactory.Options options = new BitmapFactory.Options();
BitmapFactory is static yet we are creating an instance of it?
Adding to #dasblinkenlight answer, the code could look like:
public class BitmapFactory {
public static class Options {
}
}
And that's indeed the case, see source code for BitmapFactory.
They did not name the class with a dot in it (that would be illegal). All they did was adding a static inner class called Options - a member class of the BitmapFactory class.
This is a common way of hiding classes inside their outer classes when the class or an interface in question has no meaning on its own, and must be interpreted only in the context of its outer class.
Of course the solution that you suggested (naming the class BitmapFactoryOptions) is perfectly valid as well. However, it gives a false impression that the class can be useful on its own.
Perhaps the most commonly used example of this is the Map.Entry<K,V> interface: map entries have meaning only when there is a map around them, so the nesting is very useful.
Just like any other class variable and class method, there can be class within a class as well. The following example shows all three kinds of class members accessed using the same syntax.
public class Person{
public static long totalPopulation;
public static void calculateAge(Date dob){
}
public static class Address{
}
}
All of these will be accessed in the same way. i.e.,
Person.totalPopulation = 700_000_0000L;
Person.calculateAge(person.getDOB());
Person.Address address = new Person.Address();

Class definition in java

I'm new to Java and i want a refinement:
First of all,i am not sure if i can have 2 classes in the same file.
My question is what is each class when you see this sequence of code:
class Something {
//code here
} //end of class Something
public class SomethingElse {
//NO code here!!!
public static void main(String[] args) {
//code of main here
}//end of main
}
What's the role of the class Something Else and why there is no code inside?I know that is a very stupid question but there are some details that i don't really get and i want some help...
You can have more than one class per file, but only one class can be public and its name must match the name of the file (e.g. public MyClass in MyClass.java).
The public class of a file will be visible to the outside world, and in particular if the class has a public static main(String[] args) method, it can be used to start an application.
In your case for example, once you have compiled your file using javac, you will get files Something.class and SomethingElse.class.
Using the command java SomethingElse will tell the Java Virtual Machine to do the following:
Find the SomethingElse class, which must be in the SomethingElse.class file
call the main method, matching the signature I pasted above on this class (and putting any given argument in the args array).
You cannot call java Something because the class isn't public and doesn't have a main method. But other classes in your program (and in particular, SomethingElse, can use your Something class).
You can have just one public class per file, and the file must have the same name of the class. But you can have other private classes that just the file class will see. For example:
File Something.java
public class Something {
//Something can access SomethingElse's doSomething method.
private class SomethingElse {
public void doSomething() {
}
}
}
class SomethingToo {
}
File OtherSomething.java
public class OtherSomething {
//OtherSomething cannot access SomethingElse's doSomething method.
//But can access SomethingToo, if they are in the same package
}
You can have multiple classes defined in a same file. However there should only one class defined as public and file name will be that public class name.
In the No code here!!! you can have class variables and methods defined. Your main() is one such example.
In the above file, there are two classes SomethingElse (public) and Something. Now, this is normally done when the non-public class is called internally by the public class. Also, in the above code fragment, SomethingElse seems to be a 'driver' class. In other words, it does not have any functionality/data of its own, but is used to execute (drive) other classes (probably Something in this case)
You can have nested classes, but two separate, public classes are not allowed. Each public class should be in it's own file named the same as the class.
While it's possible to have 2 classes in the same file, its considered bad practice. Besides the decreased readability, it will eventually become difficult to find out where that class declaration actually took place. Plus, if you declare a variable relating to the class, but not the class sharing the .java name, javac will most likely have issues compiling.
If you have to do it, make sure the only place you are using the second class is within the class sharing the .java name. (E.g. only use a Something object within the SomethingElse class). Otherwise, separate all your classes into separate .java files.
Yes, you can have 2 or more classes in single Java file.
The only condition is only one class will contain main method with signature(public static void main(String[] args)).
And only one public class will be there. And with that public class name you can save your file - the file name has to match the name of the public class.

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.

How to create an alias for a private inner class (using XStream)?

I'm creating aliases for long class names... It works perfectly fine, but one of the serialized classes is a private inner class. I can't think of a way to create an alias for it other than making it public. I don't like this solution, because it should not be public in the first place. But since making an alias for it will make it possible to change package and class names without having to modify XML files (because the first tag is the fully qualified class name).
This is how I create aliases:
xstreamInstance.alias("ClassAlias", OuterClass.InnerClassToAlias.class);
That's why I need public access to that inner class.
So, if anyone knows a trick to alias a private inner class, I would really like to hear about it.
You could create a class like the following and pass your reference to the xstreamInstance to the alias method.
public class Parent {
public void alias(XStream x) {
x.alias("Kiddie", Parent.Child.class);
}
private class Child {
}
}
How about using annotations for the alias?
public class Parent {
#XStreamAlias("kiddie")
private class Child {
}
}
Edit: Alas, parsing of annotations of nested classes is not supported by XStream when asking to get the parent class parsed.

Categories

Resources