How do I create a proper Java instance? - java

I have created a public class helloworld and I am trying to create an object for class Abc. I have used "new" keyword to create an instance for Abc class.But still I am getting an error "non-static variable this cannot be referenced from a static context." in 4th line.
How do I solve this problem?
public class helloworld {
public static void main (String[] args)
{
Abc obj = new Abc();
}
class Abc
{
int i;
}
}

For simplicity, put class Abc in a different file and make it a public class.
helloworld.java
public class helloworld {
public static void main (String[] args)
{
Abc obj = new Abc();
}
}
Abc.java
public class Abc
{
int i;
}
Or you can declare your class Abc as static:
public class helloworld {
public static void main (String[] args)
{
Abc obj = new Abc();
}
static class Abc
{
int i;
}
}
When you create an inner class, it follows the same rule as members of a class: Static members of a class cannot directly access Instance members. Thus, you will need to declare Abc as a static class.
PS: please use CamelCasing conventions to name your classes. Ex: Use HelloWorld instead of helloworld.
Hope this helps!

First of all: Heed Jon's advise. That said, you can quickly solve this particular problem by changing your inner class into a static class:
static class Abc {
int i;
}
I know this might seem a bit weird, but you cannot refer to regular inner classes without first creating an instance of the outer class. Since the main method is static there is no instance of HelloWorld yet. This means it cannot refer to a regular (instance-bound) inner class only to a static inner class.
Arguably a better solution is to create an instance of your class first thing in your main method:
// class names should be camel case with an upper case first letter
public class HelloWorld {
public static void main (String[] args) {
HelloWorld app = new HelloWorld();
app.start();
}
// note that this is not a static method
private void start() {
Abc obj = new Abc();
}
private class Abc {
int i;
}
}

Abc is an inner class of helloworld. To instantiate it you need an instance of helloworld
Abc abc = new helloworld().new Abc();
or make Abc a static inner class.
static class Abc {}

The first awnser is correct but don't be easy. This is the easy way for a eclipse project o similar.
Create a ABC class:
public class Abc
{
int i;
}
Import in a Hello world class and declare static:
import Abc;
public class HelloWorld{
private static Abc abc=new Abc();
public static void main(String[] args){
//do something
}
}
All IDE that you use. Help you to import the class : )

Related

Mapping a class instance to a number

I'm extremely new to Java and have been trying to use Nested class for the first time.
I have an outer class with 2 inner class and i'm trying to be able to have
the innerclass
class OuterClass {
...
class Person {
class Like {
}
**public static Map<Integer, Like> Likes;**
}
}
Is it possible in Java ?
In Golang that would look like this for example :
type Like struct {
}
type Person struct {
Name string
**Likes map[int]Like**
}
I might be going the wrong way and maybe a better OOP approch of doing that exist or is it possible this way ?
Yes this is possible and your code will be like
class Client{
class Outer{
class Phone{
class Like{
public void sayHello(){
System.out.println("Hello");
}
}
public static void method(Outer.Phone.Like g){
l.sayHello();
}
}
}
public static void main(String[] args){
Client q = new Client();
Client.Outer o = q.new Outer();
Client.Outer.Phone p = o.new Phone();
Client.Outer.Phone.Like l = p.new Like();
p.method(l); //call sayHello and print Hello
}

java - can a class type parameter from a static main class be passed to another class

I have 2 classes the static main class and class B. I'm trying to pass main to B, where there is a method that sets fields.
Can this be done?
If so, could you please provide examples?
public static void main(String[] args) {
ArrayList a = new ArrayList()
class b = new class()
b.update(b);
}
class a {
public void update(ArrayList a) {
//updates the encapsulated arrayList field
}
}
The error message keeps on saying that one is static and the other is non-static, but they should be pointing the same object
I'm not entirely sure what you are trying to do, but here is an example that shows that you can pass an instance of the main class into another class:
public class A {
private String str = null;
public static void main(String[] args) {
A a = new A();
B b = new B(a);
System.out.println(a.getStr());
}
public String getStr() {
return this.str;
}
public void setStr(String str) {
this.str = str;
}
}
public class B {
public B(A a) {
a.setA("hello");
}
}
Running this code will print out hello.
main is static and public, so you can call it from any other class as any other public static method: statically.
if you have a class A that contains a
public static void main(String[] args)
method, then class B can call this method like
A.main(s);
where s is String[]
your question is far from clear, so I suggest you to add more code samples to make it clear what you're really trying to do.

Java: concerning nested classes

I have a few classes I need: Score, Course, and handicap. The file is "handicap.java", thus the main class is "handicap".
If I try and nest the Score class or the Course class inside of the "handicap" class, I receive this error upon trying to instantiate an instance of either class:
handicap.java:129: non-static variable this cannot be referenced from a static context
Score sc = new Score(score, course);
^
handicap.java:141: put(java.util.GregorianCalendar,Score) in java.util.Map<java.util.GregorianCalendar,Score> cannot be applied to (java.util.GregorianCalendar,handicap.Score)
g.scores.put(greg, sc);
If I add "static" to the Score class declaration, I still receive the second error. Help?
The Code is here: http://pastebin.com/CvT1SCvb
take a look on this
public class Handicap {
public class Score{
}
public static class ScoreStatic{
}
public static void main(String[] args) {
Handicap h = new Handicap();
h.method();
new Handicap.ScoreStatic();
}
public void method(){
new Handicap.Score();
}
}
By the looks of it , you are getting compilation error.
Please read about the Nested Classes : http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html
This is the way it works :
public class handicap{
public static void main(String... args) {
handicap st = new handicap();
handicap.Score fl = st.new Score();
}
class Score{
//blah
}
}

Is it possible to access a variable from another class?

Is it possible to access variable abc directly from a subclass?
I know its possible by changing abc to Static, but I don't want to do this.
main:
public class main {
public subclass subclass1 = new subclass();
public boolean abc = false;
public static void main(String[] args) {
// TODO Auto-generated method stub
main menu1 = new main();
}
public main(){
while(true){
if(abc = true){
System.out.println("true");
}
}
}
}
subclass:
public class subclass {
public subclass(){
.abc = true; //possible to access abc of main?
}
}
Thanks.
Your subclass class isn't subclassing main, so it can't directly access abc. It's confusing to call it subclass, because it subclasses only Object (implicitly).
It needs to have a reference to an instance of the main class, then it can access abc through that instance. That will work because abc is public.
UPDATE
Example:
public class Main
{
public subclass subclass1;
public boolean abc = false;
public static void main(String[] args)
{
Main menu1 = new Main();
menu1.subclass1 = new Subclass(menu1);
System.out.println(menu1.abc);
}
}
public class Subclass
{
private Main myMain;
public Subclass(Main main)
{
myMain = main;
myMain.abc = true;
}
}
There are a multitude of things wrong with your code.
Subclass is not a subclass of anything, in order for it to be a
subclass it must extend another class by use of the keyword extends, Bus extends Vehicle (by default all classes in
java only extend Object).
You have declared abc as public, this
means it is accessible to everyone who has an instance of the class
main by use of the dot operator on the instance. You can achieve this by creating an instance of main in your subclass
main m = new main();
public subclass() {
m.abc = true;
}
You will also have to remove public subclass subclass1 = new subclass(); from main. The way you have made these classes subclass needs main needs subclass needs main needs subclass....circular references.
You will never be able to access an instance of the class because of the while(true) inside the constructor of main. This will run forever and never allow the constructor to finish. You will have to remove the while(true) statement, you can check whether abc has indeed been changed by doing the following
main m = new main();
public subclass() {
System.out.println("Value of abc? "+m.abc);
m.abc = true;
System.out.println("Value of abc? "+m.abc);
}
This is Simple inheritance and because abc access modifier is public, you should be able to use in child class without any issue.
If you are going to access abc, then you would have to have an instance of your main class:
Main m = new Main();
m.abc = "something";
You can use simple inheritance if both classes are related. Otherwise,
m.abc= true
Would be a good option.
If you don't make abc static it will only exist in an instance (or object) of "main".
So to access it you will need to have a reference to the object.
So one thing you could do is ask for Main in SubClass's constructor (you should follow the java conventions) like:
public class SubClass {
private final Main main;
public SubClass(Main main) {
this.main = main;
main.abc = true;
}
}
public class Main {
public SubClass subClass1 = new SubClass(this);
}
or if SubClass is really only for Main's use you could make it an inner class.
public class Main {
public class SubClass {
public SubClass() {
//You can access Main's variables here and in case of ambiguity by doing
Main.this.abc = true;
}
}
}
Alternatively you can create a Main in SubClass.
public class SubClass {
public SubClass() {
Main main = new Main();
main.abc = true;
}
}
(SubClass naming is a bit weird here and I think you might want to learn a bit more about objects/instances, or OOP in general.)
You can access abc in sub class if it extends class main. Please find below a sample
public class Test {
Boolean abc = false;
Test()
{
if(abc)
{
System.out.println("Test():True");
}
else
{
System.out.println("Test():False");
}
}
void method()
{
if(abc)
{
System.out.println("Method():True");
}
else
{
System.out.println("Method():False");
}
}
public static void main(String[] args)
{
Test1 child= new Test1();
child.method();//Parent method (abc change will reflect)
Test parent = new Test();//Directly calling parent constructor so abc is false
}
}
child class
public class Test1 extends Test
{
Test1()
{
this.abc=true;
}
}
ouput will be
Test():False
Method():True
Test():False

Getting relative inner class name in Java

package u.v;
class x {
static class xx {
static class xxx { }
}
}
While I can get the canonical ("absolute") name of the inner class
public class a{
public static void main(String[] args) {
System.out.println(x.xx.xxx.class.getCanonicalName()); //u.v.x.xx.xxx
}
}
and I can also get the last component of the class name
public static void main(String[] args) {
System.out.println(x.xx.xxx.class.getSimpleName()); //xxx
}
how would I go around elegantly getting a relative class name?
Utils.relativeClassName(x.xx.xxx.class, x.class); //xx.xxx
The following string manipulation should do the job:
xxx.class.getCanonicalName().substring(x.class.getCanonicalName().length + 1)
+1 is for . (dot) between the last outer class name and the name of interesting class.
You can use this function. The +1 is for the extra .
public static String getRelativeClassName(Class<?> inner, Class<?> outer) {
int length = outer.getCanonicalName().length();
return inner.getCanonicalName().substring(length+1);
}

Categories