why is this java initialization giving error? [duplicate] - java

This question already has answers here:
What causes error "No enclosing instance of type Foo is accessible" and how do I fix it?
(11 answers)
Closed 6 years ago.
I am trying to initialise the array C in the loop, but it gives error :
C is array of class ipdata and I have declared it and trying to initialise it inside the loop.
import java.io.*;
import java.util.*;
public class cluster_anlysis {
class ipdata{
float a,b;
int cluster;
ipdata()
{
a=0;
}
}
public float modc(float a){
if(a<0.0)
a=-a;
return a;
}
public static void main(String[] args) {
cluster_anlysis obj=new cluster_anlysis();
ipdata C[] = new ipdata[50];
float mean1,mean2,mean3;
int i,j,n1=0,n2=0,n3=0,flag=0;
float ina=0.0f;
float inb=0.0f;
//BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Scanner scan =new Scanner(System.in);
System.out.println("pls enter no of data: ");
Integer no = scan.nextInt();
System.out.println("\nnow enter the x and y values");
for(i=0;i<no;i++)
{
ina=scan.nextFloat();
inb=scan.nextFloat();
System.out.println(ina);
C[i]= new ipdata(); // this line is giving error
C[i].a=ina;
C[i].b=inb;
C[i].cluster=0;
}
}
}
What could be the problem ?
it says :
No enclosing instance of type cluster_anlysis is accessible. Must qualify the allocation with an enclosing instance of type cluster_anlysis (e.g. x.new A() where x is an instance of cluster_anlysis).

you create an instance of inner class from static methods of your outer class using the outer class instance.
c[i]= new cluster_anlysis().new ipdata();
as you have alread created cluster_anlysis instance in your first line of main method.
cluster_anlysis obj = new Cluster_anlysis();
you could simple do.
c[i]= obj.new ipdata();
read about Inner classes in java
but if you want to create an inner class instance from the non-static methods of your outer class you dont need the instance of your Outer Class .
public class OuterClass {
public void method(){
InnerClass inner = new InnerClass();
}
class InnerClass{
}
}
and also follow class name convention as posted by #A.R.S and #JB Nizet in their solutions.

It seems you're starting with Java. I would advise to avoid messing with inner classes for the moment. Define each Java class in its own file, and everything will be simpler.
Also learn about Java naming conventions:
classes start with an upper-case letter, and are CamelCased: ClusterAnalysis, IpData. They should not contain underscores.
variables start with a lower-case letter, and are camelCased: c. They should not contain underscores.
Once you are more comfortable with the basics, learn about inner classes and static inner classes in the Java tutorial. But inner classes should not be abused. The basic rule is to have one class per file.

Use outer class Instance to call inner class constructor
like
c[i]=new cluster_analysis().new ipdata();

I think the best thing to do would be to declare ipdata as static; that would eliminate the error. There should be no need to instantiate cluster_analysis in order to instantiate ipdata in this case, and it makes sense that ipdata should in fact be static.
Oh, and by convention, you might want to consider using the names IpData and ClusterAnalysis instead - class names generally start with a capital letter and are "CamelCased", as another answer also pointed out.

Related

How to get information back and forth between classes?

Hello im learning how to handle multiple classes in one code but here is a problem i couldnt figure out how it is called nor an answer to it. So i have one variable x in Back class, i get it to the main then i want to push it back to the back class and then again pull it to the main. Its a simplified code so i can use it as an example to change variables in other classes depending on certain condintions. Currently its not working.
package Classes;
public class Main {
public static void main(String[] args) {
Back Q = new Back();
double f = Q.x;
System.out.println(Q.g);
}
}
//-------------------
package Classes;
public class Back {
Main K = new Main();
double x = 10;
double g= K.f; //f cannot be resolved or is not a field
}
First of all you need to read more about access modifiers in java. There are few main things that you must understand:
Difference between static and non-static members;
Difference between different access levels (public, protected, package-private/default and private);
Local variables.
These things can help you to decide what type of variables you need.
Right now you're trying to get an access from a static main method to a non-static package-private variable in a neighbor class via newly created object, and is ok.
But you also try to get an access from the inside of a non-static object to a local variable that is defined in a static method - this is impossible. Instead, it is probably better to introduce setter methods or introduce other methods that accept external parameters.
The attribute x in class Back is package-private, so it can be accessed directly via the Back object called Q you create in main().
In the class Back you try to access the attribute f of the class Main which is references by the object called K. But the class Main does not define any attributes.
You only have a local variable called f in the scope of the main() method that has been definied in class Main.
A possible solution could be something like this. But I don't know what problem you want to solve with your code. So here is just an idea that should compile...
package Classes;
public class Main {
double d = 5.0;
public static void main(String[] args) {
Back Q = new Back();
double f = Q.x;
System.out.println(Q.g);
}
}
//-------------------
package Classes;
public class Back {
Main K = new Main();
double x = 10;
double g = K.d;
}

Creating an instance from another instance? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I'm so confused that how could it be written like this... It creates an instance from another instance
st.new FirstLevel();
public class ShadowTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
ShadowTest.FirstLevel mali = st.new FirstLevel();
}
}
Here, FirstLevel is a so-called inner class – that's because it is defined inside another class. Both relations (the 'outer' and the 'inner') are plain jane classes (and not interfaces, enums, or records). In this case, unless the inner class has the modifier static on it (and, in your code, it doesn't), then you get an instance inner class.
Such classes have a hidden field of the outer type associated with them. It is as if your FirstLevel class has this field:
private final ShadowTest outerInstance;
And each and every constructor of ShadowTest has a parameter for this field, but, it is hidden and a bit special.
Because this secret field exists, you can do things like invoke non-static methods from ShadowTest from within FirstLevel.
If you type new FirstLevel(), that just works... but only within non-static contexts inside ShadowTest. Anywhere else and the compiler will tell you that it doesn't know what instance of ShadowTest to pass along for that secret field. You can explicitly define which instance of ShadowTest. But not with new FirstLevel(shadowTestInstance), but with the somewhat weird-looking syntax shadowTestInstance.new FirstLevel(). But, it's the same thing: A parameter being passed to a constructor.
I generally advise that you do not use instance inner classes unless you really know they are the best fit for the case; this hidden field tends to cause confusion and surprises. I'd go so far as to say that you should never have instance inner classes; if you must hold a reference to an instance of the outer class, make it explicit (add an actual field, and make an actual parameter in your constructor). That way you avoid the surprises and confusion, at least. In other words, mark your FirstLevel class as static. By making your outer reference explicit, the shadowing thing also goes away; now you just have x or this.x referring to the x field in FirstLevel, and outerInstance.x for the outer field:
static class FirstLevel {
final ShadowTest shadow;
int x;
public FirstLevel(ShadowTest shadow) { this.shadow = shadow; }
}
As with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.ref.javaOO_nested
As per java syntaxes, unless it's a private or static class you could initialize it in the following way
class OuterClass {
...
class InnerClass {
...
}
}
Then a sample initialisation can be done so:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
NOTE: I have referred the block to the oracle java docs. You can read more there

In case of inner and outer classes, Java

There was one MCQ ( Multiple Choice Question ) while I was reading my Java study book and that MCQ is:
Question : In case of inner and outer classes, _________
Options are :
(a) The members of outer class can not be accessed by inner class.
(b) The members of inner class can not be accessed by outer class.
(c) Members of both can be accessed by both of the classes.
(d) None of these.
The answer given on book answer key is (b) but I'm not feeling it as right answer because outer class can access members of its inner class I think. So please help me with what is right.
Thanks, have a good day :)
lets make it simple with some code
public class A {
public int a = 1;
public class B {
public int b = 2;
public int getAfromB() { return a; } // ACCESS OUTER CLASS MEMBER IMPLICITLY
public int getBfromB() { return b; }
}
public int getBfromA() {
B myB1 = new B();
B myB2 = new B();
return myB1.b + myB2.b;
}
}
An B instance is linked to a specific A instance, it belongs to the instance scope. In its scope, the members of the A class are defined.
The A class can handle several instances of the B class. It will be able to manipulate them but cannot implicitly access a specific instance members, simply because 'b' is not unique from its perspective.
Sorry for the confusion.
You can access inner and outer classes both ways. I do suggest trying a simple example though yourself as programming is one of those things you only learn through your own problems.
Refer to this as this may help: Can an outer class access the members of inner class?

What are Keywords in Java?

I am curious about keywords in Java.
Should I understand it as a class of various methods that get created with every instance of user-defined classes, like the ultimate “super” class? How is it defined in the Java?
So for example, I came across this:
class A {
class B {}
}
A a = new A();
B b = a.new B();
This seems like each class has keyword new as its own method. I would appreciate any insights on how keywords are defined/implemented in Java.
Classes don't have keyword "new" as a personal method or anything like that. It is the Java language itself that has the keyword "new". So in other words you put "new" in the code the compiler would recognize it and instantiate a new Object.
http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.9- this link is the documentation of Java language, in section 3.9 it shows all the keywords.
Edit:
Like others are saying, what the snippet of code in your question indicates an inner class, so for instance, like it says in http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
public class ShadowTest {
public int x = 0;
class FirstLevel {
public int x = 1;
void methodInFirstLevel(int x) {
System.out.println("x = " + x);
System.out.println("this.x = " + this.x);
System.out.println("ShadowTest.this.x = " + ShadowTest.this.x);
}
}
public static void main(String... args) {
ShadowTest st = new ShadowTest();
ShadowTest.FirstLevel fl = st.new FirstLevel();
fl.methodInFirstLevel(23);
}
}
The following is the output of this example:
x = 23
this.x = 1
ShadowTest.this.x = 0
This shows that the innerclass or class B(FirstLevel) is like or similar to the outer class's variables and methods(for it is associated with the instance of the outer class) of class A(ShadowTest).
As all the languages ,Java has Keywords. Here the new keyword is used for initialization purposes.here the object of the class A is initialised in the first statement. in second statement the object of class B is initialised with class A's object A
Keywords in the simplest words are the predefined words which have some predefined specific meaning and cannot be used for any other purpose.
Check full list of keywords in Java
Now to elaborate this thing I would take example of two keywords, int and float. An int keyword is used to define an integer variable and that is all what a keyword int can do. We cannot use it for any other purpose. Similarly, float keyword can be used to define a float/decimal number variable, nothing else.
int a = 10;
I defined a variable a of integer type.
int float = 20; <----- It won't work.
In this example, I am trying to declare an integer type variable with name float, which is not possible, as float it self is a keyword, so it cannot be used as an identifier.
If we talk about new keyword, then it is used to create objects of any class or I would more precisely say, new keyword allocates memory to the objects at run time.
It is NOT like that every class has its own new keyword. new is Java's keyword so any Java class can use it.
To clarify,
A a = new A();
B b = a.new B();
In the first statement, we are creating an object of class A and as class B is the nested class of class A, so we cannot access it directly. So to access it, we are using the object of class A, which we already have built.

Static members in Java [duplicate]

This question already has answers here:
Are static methods inherited in Java?
(15 answers)
Closed 4 years ago.
I've read Statics in Java are not inherited. I've a small program below which compiles and produces 2 2 as output when run. From the program it looks like k (a static variable) is being inherited !! What am I doing wrong?
class Super
{
int i =1;
static int k = 2;
public static void print()
{
System.out.println(k);
}
}
class Sub extends Super
{
public void show()
{
// I was expecting compile error here. But it works !!
System.out.println(" k : " + k);
}
public static void main(String []args)
{
Sub m =new Sub();
m.show();
print();
}
}
The scope in which names are looked up in includes the super class.
The name print is not found in Sub so is resolved in the Super.
When the compiler generates bytecode, the call will be made to Super.print, rather than a call on a method in Sub.
Similarly the k is visible in the sub-class without qualifying it.
There is no polymorphism here, only inheritance of the contents of a name space. Static methods and all fields do not have polymorphic dispatch in Java, so can only be hidden by sub-classes, not overridden. The post you link to in your comments is using 'inheritance' in a somewhat unconventional way, mixing it up with polymorphism. You can have polymorphism without inheritance and inheritance without polymorphism.
Sub extends Super so it can see all the public/protected/package (static) members of Super.
I guess this is what you described as "Statics in Java are not inherited"
change
static int k = 2;
to
private static int k = 2;
and your Sub program won't see 'k' anymore and won't compile;
also try to create a new 'static int k=3;' in Sub, and see what happens.
It's pretty much the same as accessing Math.PI or any other global constant (which also have public and final modifiers).
In your case you have default (package) scope.
It's independed of inheritance only the scope restricts whether it is visible.
I think you might be wrong about static variables not being inherited. I suppose some properties of it are not inherited. For instance a static var normally means that all instances of the class have access to the same place in memory.
When you inherit, the derived class does not refer to the same memory as the base class.
Static member can be static data member and static method which can be accessed without using the object. It is used by nested class

Categories