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.
Related
Is it possible to access an object created in one class from another class without using parameters/arguments?
For example:
public class Main {
public static void main(String[] args) {
Two make = new Two(); // Object I created.
make.ham();
}
}
class Two {
public void ham() {
System.out.println("Ham.");
}
}
class Three {
public static void accessObject() {
// Can I access the object make here without parameters?
}
}
What I understood is that you want to access to make object, created inside Main class (Two make = new Two());. And yes, it's possible to do it.
You have to create your variable make as global and static (and it's recommended be public or protected, in case you have your classes in separate files).
So, inside your Main class, you will have to do something like:
public class Main {
public static Two make;
public static void main(String[] args) {
make = new Two(); // Object I created.
make.ham();
Three.accessObject();
}
}
As you can see, I created the make variable as static and global. This is necessary because your main method is static, and it's global to be able to be recognized by other classes. And to can call to accessObject method, I did it with the class name (because that method is static)(Three.accessObject();)
And finally inside your Three class, in the accessObject method it's necessary call to the static variable make from Main class:
class Three {
public static void accessObject() {
System.out.println("using make object from Main class in Three class...");
Main.make.ham();
}
}
As you can see now, I called the variable make with the name class Main because it's static, and finally, you will be able to call the ham method by this way.
You could you inheritance to solve your problem. For example, you would write:
class Three extends Two {
public static void accessObject() {
// You can now access the "Two" object since you have now made
// Three a subclass of Two.
}
}
EDIT:
If you wanted to say, change the implementation of the ham() method, you could do something like this:
class Two {
public void ham() {
System.out.println("Ham.");
}
}
class Three extends Two {
#Override
public void ham() {
System.out.println("I'm inside ham, but inside the Three class.);
}
}
I've 3 classes in one package. The first class (ClassStart) generates each an instance of the 2 other classes (ClassA and ClassB). I want to call in ClassB a method of ClassA by means of its instance "a".
Though the scope of Instance "a" is the package (because of the attribute "ClassA a;" in ClassStart the line "a.showText()" doesn't work. It gets the error message "a cannot resolved".
So I tried "s.a.showText()" but it doesn't work because the instance "s" was generated in a static method and I don't know how to access to "s".
The first class (contains the main-method):
public class ClassStart {
ClassA a;
public static void main(String[] args) {
ClassStart s = new ClassStart();
}
public ClassStart() {
a = new ClassA();
ClassB b = new ClassB();
}
}
The second class:
public class ClassA {
public void showText() {
System.out.println("This text comes from ClassA.");
}
}
The third class:
public class ClassB {
public ClassB() {
a.showText();
}
}
How can I call in ClassB the method "showText()" of the ClassA?
(I had looked for answers in this forum but I didn't find a answers for a three class problem like this.) Thank you for answer.
If the ClassA object needs to be the same throughout, then pass it into B:
public class ClassB {
private ClassA a;
// pass the ClassA reference into the ClassB constructor
public ClassB(ClassA a) {
this.a = a; // assign it to the a field
// a.showText(); // or you can do this if you need it called in the constructor
}
// or do this if you want the a method called in a ClassB method.
public void callAShowText() {
a.showText();
}
}
then:
public class ClassStart {
ClassA a;
public static void main(String[] args) {
ClassStart s = new ClassStart();
}
public ClassStart() {
a = new ClassA(); // create your ClassA instance
ClassB b = new ClassB(a); // pass it into your ClassB instance
b.callAShowText();
}
}
The key bit of understanding here is to understand reference types and reference variables. You want a reference variable in ClassB to refer to the ClassA object created in ClassStart. One way to do that is to pass the object into ClassB either in its constructor or in a setter method. Once you've done that, then ClassB has the reference it needs and it can call any ClassA method on the instance.
Note that you can also "solve" this by creating and using a public static ClassA variable or a public static showText() method, but in general you will try to avoid doing this since while it would work fine in a simple example like this, it doesn't "scale" well, meaning if used generally in larger more complex programs, it will risk increasing the potential connections in your complex program, greatly increasing the risk of bugs. It was for this reason, to decrease complexity and decrease connectedness (decrease coupling) that object oriented programming was created.
Make the method static:
public static void showText()
Then call it:
ClassA.showText();
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
Is there any way to acess a superclass member hidden by a subclass member using object of subclass in another class.
public class A {
int i, j;
A() {
i = 5;
j = 5;
}
}
public class B extends A {
int i;
B() {
super();
i = 10;
}
}
class TestEx {
public static void main(String[] args) {
B obj = new B();
// i from B
System.out.println(obj.i);
}
}
i need to acess i from A in testEx using obj..
same doubt is present in the case of non-static inner class.. anyway to acess variable of OuterClass in InnerClass with same name that of one in InnerClass
As simple as ((A)this).i from within the class B's instance methods or, even simpler,
A obj = new B();
System.out.println(obj.i);
Why? Because nothing except instance methods is subject to dynamic binding and overriding. The class B has all the instance variables of its ancestors.
public static void main(String[] args){
B obj=new B();
//i from B
System.out.println(((A)obj).i);
}
Expose your classes get methods via polymorphism to get the value of A's i from the instance invoked by B object. This is what you topic title is implying.
provide public get/set methods in both classes, then sit still relax and call it up.
In Python, class methods can be inherited. e.g.
>>> class A:
... #classmethod
... def main(cls):
... return cls()
...
>>> class B(A): pass
...
>>> b=B.main()
>>> b
<__main__.B instance at 0x00A6FA58>
How would you do the equivalent in Java? I currently have:
public class A{
public void show(){
System.out.println("A");
}
public void run(){
show();
}
public static void main( String[] arg ) {
new A().run();
}
}
public class B extends A{
#Override
public void show(){
System.out.println("B");
}
}
I'd like to call B.main() and have it print "B", but clearly it will print "A" instead, since "new A()" is hardcoded.
How would you change "new A()" so that it's parameterized to use the class it's in when called, and not the hard-coded class A?
Static methods in java are not classmethods they are staticmethods. In general it is not possible to know which class reference the static method was called from.
Your class B does not have a main method and static methods are not inherited.
The only way I can see this happening is to find whatever is calling A.main( String[] arg ) and change it to call B.main instead.
B.main:
public static void main( String[] arg ) {
new B().run();
}
How is your program started? Is there a batch file, shortcut, etc? Something you can change? Where does A.main get called?
I think this isn't possible. Here's why:
In Java, the implementation of a method is determined by the instance's run-time type. So, to execute B.show(), you need to have an instance of B. The only way I could see to do this, if the method that constructs the instance is supposed to be inherited, is to use Class.newInstance() to construct an instance of a type that's not known at runtime.
The problem with that is that within a static method, you have no reference to the containing class, so you don't know whose newInstance method to call.
Why do you want to do this, though? There may be some better way to achieve whatever it is you want to achieve.
In your example I wouldn't put your main method inside of A. This is setup as the entry point into the system (you can't be in B if you are specifically entering into A).
In the example below I created class A, B, and C. Class C instantiates A and B and runs them. Notice that in C I created an A, a B, and another A that I instantiate as a B. My output is:
A
B
B
Hopefully this makes sense.
public class A {
public void show(){
System.out.println("A");
}
public void run(){
show();
}
}
public class B extends A {
#Override
public void show(){
System.out.println("B");
}
}
public class C {
public static void main(String[] args) {
A a = new A();
B b = new B();
A anothera = new B();
a.show();
b.show();
anothera.show();
}
}