It is possiable to instantiate child object from parent class without child class name.
For example, I have next classes:
public class A {
protected int a;
public A1() {
a = 0;
}
public int getA() {
return a;
}
public static A getObject() {
// some code which I need to write
}
}
public class A1 extends A {
public A1() {
a = 5;
}
}
public class A2 extends A {
public A2() {
a = 10;
}
}
Usage example:
A a = A1.getObject();
a.getA(); // return 5
a = A2.getObject();
a.getA(); // return 10
a = A.getObject();
a.getA(); // return 0
A1, A2 it is not all child classes. There are may be unlimited numbers.
How can I write getObject() method to it creates A class childs instanses.
PS:
I just need to initialize child class object, but there are large amounts of child classes and I would not to call "new" for all of them and I would not to write static method to initialize it, also, all childs have same constructors. It is big lack that I can't create child instance from parent.
When you write A a = A1.getObject(),
you do use child classname (A1).
So a) your question is misleading and
b) why can't you just write A a = new A1()?
If you want to write A1.getObject(), then you can redefine getObject() in class A1:
public class A1 extends A {
public static A getObject() {
return new A1();
}
}
Without redefining, there is no way to declare getObject() in class A so that it return objects different classes because A a = A1.getObject() would compile to A a = A.getObject().
class A
{
protected int a;
public A()
{
a = 0;
}
public int getA()
{
return a;
}
public static A getObject(Class c) throws Exception
{
A obj = (A)c.newInstance();
return obj;
}
}
class A1 extends A
{
public A1()
{
a = 5;
}
}
class A2 extends A
{
public A2()
{
a = 10;
}
}
class Test{
public static void main(String args[]) throws Exception
{
A a = A1.getObject(A1.class);
System.out.println(a.getA()); // return 5
a = A2.getObject(A2.class);
System.out.println(a.getA()); // return 10
a = A.getObject(A.class);
System.out.println(a.getA()); // return 0
}
}
Related
When I'm running the below code there is no Error
class Base {
int x_of_base_class = 10;
public Base print_x() {
System.out.printf("X of Base Class = %d\n", this.x_of_base_class);
return this;
}
public Base set_x(int x) {
x_of_base_class = x;
return this;
}
}
class Derived extends Base {
int y_of_derived_class = 89;
public Derived print_y() {
System.out.printf("Y of Derived Class = %d\n", this.y_of_derived_class);
return this;
}
public Derived print_x_y() {
print_x();
print_y();
return this;
}
public Derived set_x_y(int x, int y) {
x_of_base_class = x;
y_of_derived_class = y;
return this;
}
}
public class main_class {
public static void main(String[] args) {
Derived obj = new Derived();
obj.set_x(78).print_x();
obj.set_x_y(458, 347).print_x_y();
}
}
But when I'm running the below code with the same two classes it is giving an error
public class main_class {
public static void main(String[] args) {
Derived obj = new Derived();
obj.set_x(78).print_x_y();
}
}
And Error is generated because of obj.set_x(78).print_x_y()
So, please help me to return the object of derived class from base class
You can use generics to do this:
class Base<T extends Base> {
int x_of_base_class = 10;
public T print_x() {
System.out.printf("X of Base Class = %d\n", this.x_of_base_class);
return (T)this;
}
public T set_x(int x) {
x_of_base_class = x;
return (T)this;
}
}
class Derived extends Base<Derived> {
...
I have three classes, and I need to modify first class through the second that is extended :
my first class A :
public class A{
private String name;
public void setName(String name) {
this.name= name;
}
my second class B
public abstract class B {
public void init() {
A a = new A();
a.setHost("foo");
}
}
my third class C
public class C extends B {
// I want to use the method setName() of the a declared in class B
b.init.a.setName("bar");//compile error, I tried several syntax I don't know how to do it
}
expected output, in my third class :
a.Getname = "bar"
Your code has multiple issues:
1) Variable b is never declared.
2) Variable a is private to method init, so you can't access it outside the init method.
So the solution should be like:
Class B:
public abstract class B {
protected static A a = new A(); // Protected to make it visible to child class
public void init() {
a.setHost("foo");
}
}
Class C:
public class C extends B {
public static void main(String[] args) {
a.setName("bar");
System.out.println(a.getName()); //Output = bar
}
}
you can return a in the init method of B like below.
public A init() {
A a = new A();
a.setHost("foo");
return a;
}
Then you can set the value in C like below
public class C extends B {
public setNameinA() {
B b = new B();
b.init().setName("bar");
}
}
This is my first day learning java (on my own), so I need some help.
This is my code:
public class java_main {
public static void main(String[] args) {
MyClass my = new MyClass(3,4);
MyClass your = new MyClass();
}
public class MyClass {
public int a,b;
public Myclass(int i, int j) {
a = i;
b = j;
}
public Myclass() {
a = 1;
b = 2;
}
}
}
I'm getting this error:
No enclosing instance of type java_main is accessible. Must qualify the allocation with an enclosing instance of type java_main (e.g. x.new A() where x is an instance of java_main).
Any suggestions? Thanks in advance!!!
The problem you have is that you have enclosed in java_main class MyClass
public class java_main {
public class MyClass {
}
}
Remove the java_main, to get valid result.
public class MyClass {
public static void main(String[] args) {
MyClass my = new MyClass(3,4);
MyClass your = new MyClass();
}
private final int a,b;
public Myclass() {
this(1,2);
}
public Myclass(int a, int b) {
this.a = a;
this.b = b;
}
}
The ussue you have is casued that you have to create first instance of outer class in way to be create instance of inner.
public static void main(String[] args)
{
java_main outer = new java_main();
Myclass my = outer.new Myclass(3,4);
Myclass your = outer.new Myclass();
}
The key word static apply to parts of code that is not part of object it is only enclosed by its path (a method must be in class).
Try to find a tutorial that will guide you.
You could make MyClass public:
public static class MyClass{
...
}
It works ...
public class java_main{
public static void main(String[] args) {
// TODO Auto-generated method stub
Myclass my = new Myclass(3,4);
Myclass your = new Myclass();
System.out.println("keval");
}
}
class Myclass
{
public int a,b;
public Myclass(int i, int j)
{
a = i;
b = j;
}
public Myclass()
{
a = 1;
b = 2;
}
}
change your code to this:
public class java_main {
public static void main(String[] args)
{
Myclass my = new Myclass(3,4);
Myclass your = new Myclass();
}
}
class Myclass
{
public int a,b;
public Myclass(int i, int j)
{
a = i;
b = j;
}
public Myclass()
{
a = 1;
b = 2;
}
}
Just try this,
public class java_main {
public static void main(String[] args) {
MyClass my = new java_main().new MyClass(3, 4);
MyClass your = new java_main().new MyClass();
}
public class MyClass {
public int a, b;
public MyClass(int i, int j) {
a = i;
b = j;
}
public MyClass() {
a = 1;
b = 2;
}
}
}
Better approach is move the public class into separate file
Class name should start with Capital letter as per Java naming standard.
Here, I just created an instance of java_main and by using that instance created an instance for MyClass. This is an approach if you don't want to make MyClass as static inner class.
else make MyClass as static inner class it will work but it depends on use case,
public class java_main {
public static void main(String[] args) {
MyClass my = new java_main().new MyClass(3, 4);
MyClass your = new java_main().new MyClass();
}
public class MyClass {
public int a, b;
public MyClass(int i, int j) {
a = i;
b = j;
}
public MyClass() {
a = 1;
b = 2;
}
}
}
The problem you are having is you cannot reference non-static variables (instances of MyClass) from the static context (main menu in java_main class).
Either you change your MyClass like this,
public static class Myclass
Or take out MyClass out of the java_main class. And remove the public access modifier from the MyClass. Because you cannot have two public classes in the same file.
public class java_main {
public static void main(String[] args)
{
Myclass my = new Myclass(3,4);
Myclass your = new Myclass();
}
}
class Myclass
{
public int a,b;
public Myclass(int i, int j)
{
a = i;
b = j;
}
public Myclass()
{
a = 1;
b = 2;
}
}
Hope this helps for you or someone else.
Cheers!
I want to change how a method of a class executes without overriding the method, and only overriding (or ideally extending) the inner class. Assume that I cannot change the fact that I need to do this (I am modifying an existing open source code base and there would be friction to pulling out classes or whatnot).
public class A {
static class Thing {
public int value() { return 10+value2(); }
public int value2() { return 10; }
}
public String toString() {
Thing t = new Thing();
return Integer.toString(t.value());
}
}
public class B extends A {
static class Thing {
public int value2() { return 20; }
}
}
My goal is, by changing only Thing, getting B's toString() to return "30", where currently it will return "20". The ideal would be to change only the method value2 (thus leaving any other methods unchanged), but I don't know if this is possible.
Thanks
I think you need a factory method for this. Consider the following example (derived from your snippet):
static class A {
static class Thing {
public int value() {
return 10 + value2();
}
public int value2() {
return 10;
}
}
protected Thing createThing() {
return new Thing();
}
public String toString() {
return Integer.toString(createThing().value());
}
}
static class B extends A {
static class Thing extends A.Thing {
public int value2() {
return 20;
}
}
#Override
protected Thing createThing() {
return new Thing(); // creates B.Thing
}
}
public static void main(String[] args) {
System.out.println(new B());
}
Output:
30
You should be able to just extend the inner class with Thing extends A.Thing. As long as it's visible in your scope it shouldn't be a problem.
It's not possible by only changing value2. The problem is that 'new' calls aren't dispatched dynamically - the 'new' in toString will always create A::Thing. You could fix this creating a factory : something like this:
public class A {
static class Thing {
public int value() { return 10+value2(); }
public int value2() { return 10; }
}
private Thing makeThing() { return new Thing(); }
public String toString() {
Thing t = new Thing();
return Integer.toString(t.value());
}
}
public class B extends A {
static class Thing extends A.Thing {
public int value2() { return 20; }
}
private Thing makeThing() { return new Thing(); }
}
I have 2 classes:
public class A
{
int n = 10;
public int getN()
{
return n;
}
}
public class B extends A
{
int n = 20;
public int getN()
{
return n;
}
}
public class Test
{
public static void main(String[] args)
{
B b = new B();
System.out.println(b.getN()); //--> return 20
System.out.println(((A)b).getN()); //--> still return 20.
//How can I make it return 10?
}
}
All methods in Java are always virtual. That is, there is no way of invoking the "super"-version of the method from the outside. Casting to A won't help as it doesn't change the runtime type of the object.
This is probably your best alternative / workaround:
class A {
int n = 10;
public int getN() {
return n;
}
public final int getSuperN() { // "final" to make sure it's not overridden
return n;
}
}
class B extends A {
int n = 20;
public int getN() {
return n;
}
}
public class Main {
public static void main(String[] args) {
B b = new B();
System.out.println(b.getN()); // --> return 20
System.out.println(((A)b).getN()); // --> still return 20.
System.out.println(b.getSuperN()); // --> prints 10
}
}
you can't make the value be "10" because the instance of the object was for class B, and when you do the cast the only thing that are you doing is changing the define class not setting values for the object B, in other words if you need to get 10 its' something like this
b = new A();
That thing won't work due to polymorphism. Class B is still class B even if you cast it into its super class.
I think you'll need something like this:
public class B extends A
{
int n = 20;
/**
* #return the super n
*/
public int getSuperN()
{
return super.n;
}
}
What you see is polymorphism in action. Since b is a B, that method (which returns 20) is always called (regardless if you cast it to an A).