Android and Java and data classes - java

I am relatively new to working with Java and have come from a C/C++ background.
In my app I am needing a number of classes which will simply hold data.
Rather than have one file per data class, I thought of simply putting all the classes inside a basic class.
Here is what I am declaring -
public class InternalData
{
public class LocalSearchDef
{
public String m_sAdresse = null;
public GeoPoint m_gpPoint = null;
public int m_iSearchRadius = 0;
}
public class GeoBounds
{
public double m_dNELat;
public double m_dNELng;
public double m_dSWLat;
public double m_dSWLng;
}
}
However, eclipse tells me that there is "No enclosing instance of type InternalData is accessible. Must qualify the allocation with an enclosing instance of type InternalData (e.g. x.new A() where x is an instance of InternalData).", when I try to create a new instance of, say, GeoLocation I get the error.
This happens with either :
GeoLocation gl = new GeoLocation();
or
GeoLocation gl = new InternalData.GeoLocation();
Can anyone point me in the right direction please ?

You would need to make the internal classes static.
public static class Foo {
}

Although you can do it using a static declaration, don't try to do it this way.
If you are going to encapsulate classes within another, they should have some relationship to the enclosing class (like Map.Entry to Map). You are simply trying to organize multiple classes into the same file by making a holder class, that serves no purpose.
There is nothing wrong with one class per file, this is the standard Java approach. You need to justify why they should be in the same file, not the other way around.
You may also want to declare your classes with accessor methods not simply create data structs with all public access to the data members. This is poor OO.

You're trying to use a non-static inner without an instance of InternalData for it to belong to.
See: An enclosing instance that contains <my reference> is required

Related

Accessing private method from different instance of the same class

I just came across a code.In one case i am not able to access the private members of the class using its instance (which is fine) but in other case i am able to access the private members with its different instance (belongs to the same class). Can anyone please explain me why its happening?
class Complex {
private double re, im;
public String toString() {
return "(" + re + " + " + im + "i)";
}
Complex(){}
/*Below c is different instance, still it can access re,im( has a private access)
without any error.why? */
Complex(Complex c) {
re = c.re;
im = c.im;
}
}
public class Main {
public static void main(String[] args) {
Complex c1 = new Complex();
Complex c2 = new Complex(c1);
System.out.println(c1.re); /* But getting an error here ,
which is expected as re and im has a private access in Complex class.*/
}
}
You can access private members from any code block that is defined in the same class. It doesn't matter what the instance is, or even if there is any instance (the code block is in a static context).
But you cannot access them from code that is defined in a different class.
Your first reference is in the same class, Complex, which is why it works. And the second is in a different class, Main, which is why it doesn't work.
The reason is class Main cannot access to private fields of other classes. In this case to the private fields of Complex class.
You can access to private fields in Complex class only from methods in this class. In other words, if you move main method to Complex class the code will be compiled.
If you want to get/set values in Complex class from Main (or other classes) you should add setters/getters in Complex class.
Here is the table explaining access modifiers:
As you can see, in the private row, everything is N except for the column Class. That means you can access private members as long as you are accessing them in the same class as they are declared. You can even access private non-static members from a static context in the same class using an instance. There is no access modifier that only allows access from the same instance.
Why?
Because figuring out whether this and c are the same instance at compile time is a pain. You have to actually run the code to see if they are referring to the same instance or not.
Conceptually the access specifiers are # class level, not # instance level.
Following could be the reasons to keep access specifiers # class level.
From JLS Documentation, we can clearly see that the access is for users, who are implementing(or using a class/package) based on the contract.
To put in simple terms, as a developer(users) all I am concerned is what are the members(variables,methods) available, and what they do, how I can use them(the base of abstraction concept).
In your case, it is the same class and it has all the privilege to access its member and hence the observed behaviour.

How to create variable accessible by multiple classes and multiple methods in Java

I would like to create a global variable in my Java program, or at least one that can be accessed by multiple methods of multiple classes. I'm fluent in C, VB6, Jovial, and many other languages, but I don't get Java. I chose it ONLY for WindowBuilder!
Here is some Java-like pseudocode for what I want, minimal to show what I am trying to do. I am aware that it doesn't compile as-is; the point I am focusing on is the NumberOfMembers variable -- how it should be declared and accessed:
public class Prelim {
public String FileName;
public int NumberOfMembers; //instantiate? I've tried all I know
//to do so! Instantiate where, all methods that use?
private void myMethod_a() {
FileName = "C:\myfilename";
ReadRoster();
//modify roster
WriteRoster();
System.out.println(NumberOfMembers);
}
}
public class ReadWriteRoster /* maybe extends Prelim?? */ {
public void ReadRoster(){
//read roster file using FileName
NumberOfMembers = 100;
}
public void WriteRoster(){
//write roster file using FileName
for (int num = 0; num < NumberOfMembers; num++){
}
//do the write`enter code here`
}
}
}
You can use "static" key Word example
static int i = 3;
With this you can access to the variable i in all class of The package and you can import this in all other package.
Java does not offer global variables in the same sense that C and some other languages do. Every variable is associated with a specific class, and often with a particular instance of that class. These two alternatives are distinguished by use of the static keyword, which indicates that the variable (or method or nested class) is associated only with its host class, not with any particular object of that class.
Probably the simplest way to achieve what you asked starts with declaring NumberOfMembers statically, like so:
public class Prelim {
// ...
public static int NumberOfMembers;
// ...
}
Then, everywhere you want to reference it in any other class, you need to qualify its name with the class to tell Java which variable of that name you mean:
// ...
Prelim.NumberOfMembers = 100;
// ...
Although it is not strictly necessary, as a matter of style I recommend using the qualified form even inside the host class.
With that said, what little I see of your code underscores your admission that you don't get Java. Classes should represent things, and to reinforce that to yourself and others, their names should be nouns or noun phrases.
You seem instead to be organizing your classes around steps in your processing algorithm. This leads to a pretty arbitrary arrangement of your code, and directly to some of the questions in code comments about instantiating class Prelim. You are trying to write procedural code, but dressing it up in object-oriented form. You can write procedural code in Java, but it is likely that your task would accommodate a bona fide object-oriented approach as well.
At first glance, an object-oriented version of your code might involve turning it inside out: it looks like it at least wants a class Roster with an instance variable numberOfMembers and methods read() and write(). Those methods could refer to the instance variable naturally, because they would be referring to a member variable of the same object. That would also better accommodate having multiple rosters in the program at the same time, each with its own number of members.
More complex example is using enum types. It is a good practice using enum as singleton.

Instantiation of Outer Class From Inner Class Instance?

I have found below example in one of the answers:
Java inner class and static nested class
public class Container {
public class Item{
Object data;
public Container getContainer(){
return Container.this;
}
public Item(Object data) {
super();
this.data = data;
}
}
public static Item create(Object data){
// does not compile since no instance of Container is available
return new Item(data);
}
public Item createSubItem(Object data){
// compiles, since 'this' Container is available
return new Item(data);
}
}
I want to know why we do something like this: i.e. To get the instance of container why we create the instance of inner class? What is the use of this approach? Which design pattern it is?
The above approach is already being used in one of the maintainance project, and I still didnt get whats the use of it?
The main purpose of this construct is the management of data. That the inner class hands out references to the "container" is just an unimportant implementation detail.
The problem with abstract and abridged examples like yours is: You just transfer the "how" from the writer to the reader of the code. But the "why" is completely lost.
So you can just replace Container with FileSystem and Item with File and data with some more internal state to a file. Then you can see:
A filesystem can have one or more files.
A file is exactly in one filesystem.
The lifetime of the File cannot exceed the lifetime of the filesystem.
The implementation between File and Filesystem is tightly coupled - each one might call the other - even private methods.
The last point is IMO the most important one: You can offer the slim and safe public API to the real user while File and Filesystem can use dangerous private methods of each other. In case of a Filesystem you don't want to grant anyone else access to these dangerous methods.
These traits are common for some problems - hence they are used.
I want to know why we do something like this: i.e. To get the instance of container why we create the instance of inner class?
That is not what is happening.
In fact, you cannot create the instance of the inner class Item unless you already have an instance of the outer class Container on which you can call the createSubItem method. Creating the inner class instance doesn't create a new instance of the outer class. Rather it creates it in the context of the existing instance ... the one that is "available" when you invoke the inner classes constructor.
the method in question is defined as static so it can access only static members of the class and since the Item class is not declared as static inner class it can't be accessed from a static function.
I am not sure about this specific design pattern or why it is required but this can work:
public static Item create(Object data) {
Container c = new Container();
return c.new Item(data);
}
One of the places we have used such design is just for having additional Comparator classes.

Is there an info-graphic that explains java variable inheritance and constructor code flow?

Is there an info-graphic that explains java variable inheritance and constructor code flow?
I'm having troubles visualizing how inheritance and class variables work, public, static private default or otherwise.
The Java Tutorials from Oracle have a section all about Inheritance and should be able to answer most of your questions.
I would refer you to go with Lava Language Specification and try to write the code using above keywords and then test it.
default: Visible to the package. .
private: Visible to the class only
public: Visible to the world
protected: Visible to the package and all subclasses .
The access modifier (public, protected, package) plays only a small role in inheritance. You can't make a function or variable in a subclass less accessible than the superclass (e.g., Animal has public void doStuff() and Cat extends Animal has private void doStuff()
Static and non-static methods don't really affect inheritance either. Static variables work the same way, except relative to the class of interest
public class Magic{
public static int pants;
}
public class MagicPants extends Magic{
public void go(){
System.out.println(pants);
System.out.println(MagicPants.pants);
System.out.println(Magic.pants);
}
public static void main(String argv[]){
Magic.pants = 2;
MagicPants.pants = 1;
new MagicPants().go();
}
}
All print 1
Constructor code flow is easy - follow the super() calls.
So i don't know graphics.
Static means the variable is the same for all object which have the same class.
Like
public Class TryVariable{
public static int variable = 2
public static void main(String[] args){
a = new TryVariable()
b = new TryVariable()
system.out.println(a.variable)
system.out.println(b.variable)
// both equals 2
a.variable= 3
system.out.println(a.variable)
system.out.println(b.variable)
// both equals 3, because variable is static.
}
Public variable means you can directly change directly her by the way i do in ma previous example: object.variableName = value.
This is dangerous, all people inadvisable to use it.
Private variable can't be change directly you need to use somes getters and setters to do this work. It's is the good way to code.
The defaut, i'm not sur of all parameters so i don't describe to you. But 99.9% of time the private is use.
Protected mean, the variable is open to packages and sub classes (in first time private is easier to use and safer)
An other parameter can be final, with this parameter the variable can't be change any more. It's like a constant. And a static final parameter is a class constant.
If you need more information, previous response explain where are find the officials sources.
This is very easy example: http://vskl.blogspot.cz/2009/05/polymorphism-in-java.html
every time you create Circle or Square object, Shape object is created too
About the variables:
- private fields are not accessible by any other class including subclasses.
- protected fields are accessible by any subclass. Taken the picture from the link, variables x and y of abstract class Shape, every instance of Circle or Square have these fields.
- default fields are accessible by any subclass and by any class in the same package(only in same package, classes in subpackages do not have access). This is useful typicaly when writing automated test, you don't have to declare public getter for the field.
- public fields are accessible by any other class. However using those is not a clean way how to write code, it is better to create private field with getter and setter.
- static keyword designates field owned by class, not by it's instances. It is like having one field shared by multiple instances of the class. If one instance changes value of this field, every other instance can read only this new modified

Java Variables Basics

Ok, so I am about to embarrass my self here but I am working on a project that I will need to get some help on so I need to get some conventions down so I don't look too stupid. I have only been doing java for 2 months and 100% of that has been on Android.
I need some help understanding setting up variables and why I should do it a certain way.
Here is an example of my variables list for a class:
Button listen,feed;
Context context = this;
int totalSize = 0;
int downloadedSize = 0;
SeekBar seek;
String[] feedContent = new String[1000];
String[] feedItems = new String[1000];
ListView podcast_list = null;
HtmlGrabber html = new HtmlGrabber();
String pkg = "com.TwitForAndroid";
TextView progress = null;
long cp = 0;
long tp = 0;
String source = null;
String pageContent = null;
String pageName = "http://www.shanescode.com";
DataBaseHelper mdbHelper = new DataBaseHelper(this);
int songdur = 0;
So all of these are variables that I want to use in all through the whole class. Why would I make something a static, or a final. I understand Public but why make something private?
Thanks for your help and please don't be too harsh. I just need some clarification.
These words all alter the way the variable to which they are applied can be used in code.
static means that the variable will only be created once for the entire class, rather than one for each different instance of that class.
public class MyClass{
public static int myNumber;
}
In this case the variable is accessed as MyClass.myNumber, rather than through an instance of MyClass. Static variables are used when you want to store data about the class as a whole rather than about an individual instance.
final prevents the variable's value from changing after it is set the first time. It must be given an initial value either as part of its declaration:
public final int myNumber = 3;
or as part of the class's constructor:
public MyClass(int number){
this.myNumber = 3;
Once this is done, the variable's value cannot be changed. Keep in mind, though, that if the variable is storing an object this does not prevent the object's variable from being changed. This keyword is used to keep a piece of data constant, which can make writing code using that data much easier.
private modifies the visibility of the variable. A private variable can be accessed by the instance which contains it, but not outside that:
public class MyClass{
private int myNumber;
public void changeNumber(int number){
this.myNumber = number; //this works
}
}
MyClass myInstance = new MyClass();
myInstance.myNumber = 3; //This does not work
myInstance.changeNumber(3) //This works
Visibility is used to control how a class's variables can be used by other code. This is very important when writing code which will be used by other programmers, in order to control how they can access the internal structure of your classes. Public and private are actually only two of the four possible levels of visibility in Java: the others are protected and "no (visibility) modifier" (a.k.a not public or private or protected). The differences between these four levels is detailed here.
static = same for all instances of a class.
final = unchanging (reference) for a particular instance.
If you needed some field (aka a class variable) to be shared by all instances of a class (e.g., a constant) then you might make it static.
If you know some field is immutable (at least, it's reference is immutable) in an instance, then it is good practice to make it final. Again, constants would be a good example of a field to make final; anything that is constant within an instance from construction time on is also a good candidate for final.
A search for "java final static" gives pretty useful further reference on the use of those keywords.
The use of the private keyword controls what can accessed by other classes. I'd say it's biggest use is to help developers "do the right thing" - instead of accessing the internals of the implementation of another class, which could produce all sorts of unwanted behavior, it forces using accessor/mutator methods, which the class implementor can use to enforce the appropriate constraints.
Private
The idea behind using private is information hiding. Forget about software for a second; imagine a piece of hardware, like an X-Box or something. Somewhere on it, it has a little hatch to access the inside, usually sporting a sticker: "open this up and warranty is void."
Using private is sticking a sticker like that in your software component; some things are 'inside' only, and while it would be easy for anyone to open it up and play with the inside anyways, you're letting them know that if they do, you're not responsible for the unexpected behavior that results.
Static
The static keyword does not mean "same for all instances of a class"; that's a simplification. Rather, it is the antonym of "dynamic". Using the static keyword means "There is no dynamic dispatching on this member." This means that the compiler and not the run-time determines what code executes when you call this method.
Since thee are no instances of objects at compile-time this means that a static member has no access to an instance.
An example:
public class Cat {
public static void speak() { System.out.println("meow"); }
}
public class Lion extends Cat {
public static void speak() { System.out.println("ROAR"); }
}
// ...
public static void main(String argv[]) {
Cat c = new Lion();
c.speak();
}
The above prints "meow" - not "roar" - because speak is a static member, and the declared type of c is Cat, so the compiler builds in such a way that Cat.speak is executed, not Lion.speak. Were there dynamic dispatching on static members, then Lion.speak would execute, as the run-time type of c is Lion.
Another thing that might trip you up is this:
Not everything has to be a class level variable; you should have a variable defined for the smallest scope it needs to be defined.
So as an example, suppose your class only has one method which uses your TextView progress variable. Move that declaration into the method that needs it. This way it tidies things up and helps you make more robust code by separating out things that are really separate.
I don't know why you would make anything private.
Folks will chime in and say that private is a Very Important Thing.
Some folks will claim that you can't do encapsulation without private. Most of this seems to be privacy for privacy's sake.
If you are selling your code to someone else, then you must carefully separate the interface elements of your class from the implementation details of your class. In this case, you want to make the implementation private (or protected) so that -- for legal purposes -- the code you sell doesn't expose too much of the implementation details.
Otherwise, if you're not selling it, don't waste a lot of time on private.
Invest your time in separating Interface from Implementation. Document the Interface portions carefully to be sure you're playing by the rules. Clearly and cleanly keep the implementation details separate. Consider using private as a way to have the compiler "look over your shoulder" to be sure you've really separated interface from implementation.
One of the aspects of the object oriented approach that has made it so wildly popular is that you can hide your variables inside of a class. The class becomes like a container. Now you as the programmer get to decide how you want the users of your class to interact with it. In Java, the tradition is to provide an API -- a public interface for your class using methods of the class.
To make this approach work, you declare your variables as private ( which means only methods within your class can access them ) and then provide other methods to access them. For example,
private int someNumber;
This variable can only be accessed from within your class. Do you think others might need access to it from outside of the class? You would create a method to allow access:
public int getSomeNumber()
{
return someNumber;
}
Perhaps users of your class will also need the ability to set someNumber as well. In that case, you provide a method to do that as well:
public void setSomeNumber( int someNumber )
{
this.someNumber = someNumber;
}
Why all of this work just to get access to a class member that you could just as easily declare as public? If you do it using this approach, you have control over how others access the data in your class. Imagine that you want to make sure that someNumber only gets set to be a number < 100. You can provide that check in your setSomeNumber method. By declaring your variables to have private access, you protect your class from getting used incorrectly, and make it easier on everyone who needs to use it -- including yourself!
Declaring a variable to have static access means that you do not need an instance of the class to access the variable. In Java, generally you write a class and then create an instance of it. You can have as many instances of that class as you want, and they all keep track of their own data. You can also declare variables that are part of the class itself, and this is where the static keyword comes in. If you create a variable...
static int classVariable = 0;
the variable can be accessed without a class instance. For example, you might see this done from time to time:
public static final int MY_CONSTANT = 1;
While there are better ways to do this now, it is still a common pattern. You use this variable without any instance of the class like this:
myInstance.setSomeNumber( MyClass.MY_CONSTANT );
java.awt.Color uses static variables this way. You can also declare methods to be static ( look at public static void main, the starting point for your programs ). Statics are useful, but use them sparingly because creating instances of classes can often result in better designs.
Finally ( pun intended ), why would you ever want to declare a variable to be final? If you know that the value should never change, declaring it as final means that if you write some code that tries to change that value, the compiler will start complaining. This again helps protect from making silly mistakes that can add up to really annoying bugs.
If you look at the static variable example above, the final keyword is also used. This is a time when you have decided that you want to make a variable public, but also want to protect it from being changed. You do this by making it public and final.

Categories

Resources