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
Related
I was revising some of the old school concepts of Java in order to solve one problem . I have written the following code where i am trying the create objects of multiple class in that same classes and calling the methods with those objects from the main.
class a {
public void display() {
System.out.println("inside class a");
a a1= new a();
}
}
class b {
public void display() {
System.out.println("inside class b");
b b1= new b();
}
}
public class one {
void display() {
System.out.println("inside class one");
}
public static void main(String[] args) {
one o = new one();
a1.display();
b1.display();
o.display();
}
}
I am getting object cannot be resolved error. My question is what i need to change to let the above code work. And, do i need to always declare objects inside the main().
Any help will be highly appreciated
I'm not really sure why you would want to do that, but assuming you're just wondering about the possibility to implement such a thing - yes, it can be done.
You can create an instance of a class inside that same class, like so:
public class A {
public static A instance = new A();
public void display() {
System.out.println("inside class A");
}
}
Pay attention to the static modifier in the above code; it allows you now to access instance from another place (class, method, main) like so:
A.instance.display();
If you want to know whether you can declare a variable inside a method, and not a class, and make it accessible from another method, then the answer is - no, you cannot.
Yes you need to declare objects inside the main()
class a {
public void display() {
System.out.println("inside class a");
}
}
class b {
public void display() {
System.out.println("inside class b");
}
}
public class one {
void display() {
System.out.println("inside class one");
}
public static void main(String[] args) {
a a1= new a();
b b1= new b();
one o = new one();
a1.display();
b1.display();
o.display();
}
}
Don't know what you want to achieve and yes you should create object of class a and class b inside main functions to use instance methods of these classes.
package com.stack.overflow;
class a
{
public void display()
{
System.out.println("inside class a");
//a a1= new a(); ---> No need of this line as you can
// directly access instance variables and methods directly without
// creating any object or you can also use **this** keyword for the same
}
}
class b
{
public void display()
{
System.out.println("inside class b");
//b b1= new b(); ---> No need of this line as you can
// directly access instance variables and methods directly without
// creating any object or you can also use **this** keyword for the same
}
}
public class one
{
void display()
{
System.out.println("inside class one");
}
public static void main(String[] args) {
one o = new one();
a a1=new a();
b b1=new b();
a1.display();
b1.display();
o.display();
}
}
You may find the answer to your confusion easily - #ratul-sharker : a1 & b1 must be declared and instantiated inside the main. as well as other answers here correcting your code.
The real question is your notion of scoping and lifetime of variables - Not only a1 and b1 lie inside the classes a and b but they have been instantiated inside methods so they are local. So, try to understand the difference between field variables and local variables - their lifetimes and scopes are vastly different.
Accessing a local variable directly like that(which will be instantiated when the method is called) is like asking asking for a result from future in the present. Note that field variables will remain as long as object is alive but the local variables will remain only for the duration of the method call.
Hope it is clear to you now.
Also, your question:
My question was is it possible to create an object of an class in the
same class and call it from main?
Yes. Because main is a static method so it is not bound to an object like non-static method does. static methods are class level while non-static methods are object level. You can also create an instance in a non-static method for that matter.
How to stop other classes to create the object of the class using new operator in java. For Example, i have one class A. i don't want any other class to create its object using new operator.
One Approach is that i can throw IllegalArgumentException in the constructor of class A.
is there any other?
public class A{
public A(){
throw IllegalArguementException();
}
}
The approach what you followed is wrong.. you can't create object of your class as well with this approach.
So you must make your construction private and write static method to get the instance of the class.
class Test
{
private Test(){ }
public static Test getTestInstance(){
return new Test();
}
}
Hope it helps,
You can do it by making the constructor private.
class A
{
int i;
private A()
{
i=1;
}
public static A getInstance()
{
return new A();
}
}
class B
{
A a;
public B()
{
/* a=new A(); //This doesn't compile */
}
}
Implementing Singleton in Java 5 or above version using Enum is thread safe and implementation of Singleton through Enum ensures that your singleton will have only one instance even in a multithreaded environment.
public enum SingletonEnum {
INSTANCE;
public void doYourStuff(){
System.out.println("Singleton using Enum");
}
}
And this can be called from clients :
public static void main(String[] args) {
SingletonEnum.INSTANCE.doYourStuff();
}
You can make the class abstract (though in this case no instance of this class can be instantiated by any class, so perhaps it's not what you want), or make the constructor private.
private A() {}
Make the constructor private.
This question already has answers here:
Why can't we have static method in a (non-static) inner class (pre-Java 16)?
(15 answers)
Closed 8 years ago.
Im trying to understand how inner class works and while experimenting with some simple code i got a error : The method hello cannot be declared static; static methods can only be declared in a static or top level type
on this code
public class Class1 {
public static void main(String[] args) {
Class1 c = new Class1();
c.show();
}
public static void show() {
class C2 {
static public void hello() {
System.out.println("show class");
}
}
C2.hello();
}
}
and i cant understand why!
Refer to the documentation here.
Inner Classes: 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.
Class2 is an inner class which means that it needs to be tied to an Class1 object. Then objects of Class2 can access the fields of the bound object at all times:
public class Class1 {
private String name = "class1";
public static void main(String[] args) {
Class1 a = new Class1();
Class2 c = a.new Class2();
c.show();
}
class Class2 {
public void show() {
System.out.println("helloworld: "+name); //accessing the name field of a without needing the variable
}
}
}
or you need to make Class2 static so it doesn't need the Class1 instance.
public class Class1 {
public static void main(String[] args) {
Class2 c = new Class2();
c.show();
}
static class Class2 {
public void show() {
System.out.println("helloworld");
}
}
}
Class C2 in your example above is a local Inner class, which means an inner class defined within a method of an outer class, and such classes cannot have static methods inside them because they are associated with objects, (static methods are not dependent upon objects).
Moreover, a local inner class must be instantiated within the method it has been created and not outside the method. This is a rule.
try modifying your code in following way:
public class Class1 {
public static void main(String[] args) {
Class1 c = new Class1();
c.show();
}
public static void show() {
class C2 {
public void hello() {
System.out.println("show class");
}
}
C2 obj= new C2();
obj.hello();
}
}
This should work.
You cant do this since you need to create an instance of Class 'Class1' before you can access Class 'C2'. However the method 'hello' should be possible to access without creating an instance (being a static method).
public interface Bsuper {
abstract class A {
abstract void test1();
void test2() {
System.out.print("test2 ");
}
}
}
// second file
public class Bsub extends Bsuper.A {
void test1() {
System.out.print("test1 ");
}
}
// third file
public class Bsubmain {
public static void main(String args[]) {
Bsub sub1 = new Bsub();
Bsuper.A obj = new Bsub();
sub1.test1();
sub1.test2();
obj.test1();
obj.test2();
}
}
It produces the output as expected test1 test2 test1 test2, but my question is in the Bsuper class, class A is static we all know that and now with the abstract keyword it becomes abstract class, but how is it possible to have both abstract and static applied to class at the same time.Is class A really static also or is there any other explanation for it.Please answer!!
how is it possible to have both abstract and static applied to class at the same time.
It is perfectly valid to have a static abstract class. This is different from having a static abstract method, which doesn't make sense, as you can't override such methods, and you're also making it abstract. But with static class, you can of course extend it, no issues. Making it abstract just restricts you with creating an instance of it.
So, even this is valid:
class Main {
static abstract class Demo { }
class ConcreteDemo extends Demo { }
}
In which case, you can't instantiate Demo, and sure you can instantiate ConcreteDemo.
Remember that a static inner class is using a different concept of static.
In this case it means that the inner class does not have access to the outer class's instance variables.
public class Test {
long n = 0;
static class A {
// Not allowed.
long x = n;
}
class B {
// Allowed.
long x = n;
}
}
Making them abstract does not change anything.
abstract static class C {
// Not allowed.
long x = n;
}
abstract class D {
// Allowed.
long x = n;
}
i'm relativly new to java and experimantating a bit with javafx
i want to change a variable from class A while using a method from class B
Main: thats the main class, it contains all the needed stuff(shows the primaryStage etc) it does have an constructor, so its not creating an actual "main-object"
public class Main extends Application {
Sub sub = new Sub();
int a;
// stuff
public void aMethod() {
sub.subMethod();
}
}
Sub: this class solely surpose is to change the variable a, it does not contain a constructor to create a "sub-object"
public class Sub {
//stuff
subMethod(){
int a = 5;
}
if i put the line Main main; in the Sub class, the program will give me a nullpointer exception, if i'm calling the subMethod().
ok...i guess cause i didnt actually create the main object... so far so good.
BUT... if i put in the line Main main = new Main(); the program wont even start giving me an "exception while running application" error
the strange thing though is, if i put the line Main main = new Main(); in the subMethod...
subMethod(){
Main main = new Main();
int a = 5;
}
...the damn thing actually works...(well its slow, guess because with every calling of the method its creating a new object)
why is that so?
and how is it done correctly? :)
(using methods of other classes to "overwrite" variables)
regards
Red
You should not create more than one instance of Main in your program. Probably Main is not the best place to store mutable state (class members), but if you want that, you need to pass the instance of Main to subMethod (and make a public, or provide a public setter method):
public class Main extends Application {
Sub sub = new Sub();
public int a;
// stuff
public void aMethod() {
sub.subMethod(this);
}
}
public class Sub {
//stuff
subMethod(Main main){
main.a = 5;
}
So you want a method to change the value of another class's fields. There are a few ways to do this. If you have this class
public Class A {
private int a;
...
public void setA(int a) {
this.a = a;
}
}
You can do something like this
public Class B {
private static A instance;
....
public static void setA(int a) {
instance.setA(a);
}
}
Or you can take the A in as a parameter to the set method
public Class B {
...
public static void setA(A a, int val) {
a.setA(val);
}
}
If you want direct access to the fields on A you have to make them public (this is usually not what you want to do as it gives complete access rather than just giving just the access the other classes require)
Public Class A {
public int a;
...
}
Then you can do
Public Class B {
...
public static void setVal(A a, int val) {
a.a = val;
}
}
Also if you don't have the method setA in B as static you'll have to call it on an instance of B like
B b = new B();
b.setA(a, val);
Where as if it's static you call it on the class B
B.setA(a, val);