Please run output of below two programs...
Program_1:
package p1;
class x {
public void methodA() {
System.out.println("Methos A of Class X");
}
}
class y extends x {
public void methodA() {
System.out.println("Method A of Class Y");
}
}
class Override1 {
public static void main(String[] args) {
x obj1 = new x();
x obj2 = new y();
y obj3 = new y();
/* y obj4 = new x(); */
obj1.methodA();
obj2.methodA();
obj3.methodA();
/* obj4.methodA(); */
}
}
Program_2 :
class x {
int a[] = new int[2];
x() {
a[0] = 10;
a[1] = 20;
}
}
class y extends x {
int a[] = new int[10];
y() {
a[0] = 12000;
a[1] = 1000;
a[2] = 120;
}
}
class Override2 {
public static void main(String[] args) {
x obj1 = new x();
x obj2 = new y();
// y obj3 = new x();
y obj4 = new y();
System.out.println(obj1.a[1]);
System.out.println(obj2.a[1]);
System.out.println(obj4.a[1]);
}
}
My specific question is that in Program_1 by what means MethodA of class Y Called? and in program_2 by What means '20' (a[1]) of class X is called?
please clear my basic concept about creation of object regarding memory allotment and reference assignment.
The short answer is that there is no data polymorphism in Java.
In the first example, methodA is the same method implemented in different classes.
In the second example, the two a are completely separate, unrelated data members (even though they happen to have the same name and data type).
The second example is equivalent to:
class x {
int a_x[] = new int[2];
x() {
a_x[0] = 10; a_x[1] = 20;
}
}
class y extends x {
int a_y[] = new int[10];
y() {
a_y[0] = 12000; a_y[1] = 1000; a_y[2] = 120;
}
}
class Override2 {
public static void main(String[] args) {
x obj1 = new x();
x obj2 = new y();
y obj4 = new y();
System.out.println(obj1.a_x[1]);
System.out.println(obj2.a_x[1]);
System.out.println(obj4.a_y[1]);
}
}
My specific question is that in Program_1 by what means MethodA of class Y Called? --> Its called Dynamic Dispatch mechanism (Method overriding). check here. Here, the method of the RHS (instance type) is called irrespective of the reference on the LHS (child / parent), provided the parent defines the same method.
What means '20' (a[1]) of class X is called --> depends on the type of reference. If reference is of X x.field is called irrespctive of RHS.
Related
class X {
protected int v = 0;
public X() {
v += 10;
}
public void proc(X p) {
System.out.println(43);
}
}
class Y extends X {
public Y() {
v += 5;
}
public void proc(X p) {
System.out.println(57);
}
public int getV() {
return v;
}
}
class Z extends Y {
public Z() {
v += 9;
}
public void proc(Z p) {
System.out.println(39);
}
}
class Main {
public static void main(String[] args) {
X x = new Z();
Y y = new Z();
Z z = new Z();
x.proc(z);// 1
System.out.println(y.getV());
}
}
From what I can understand,the method proc() is called on an object of type X that "holds" a type Z and at runtime JVM checks the object's type and overrides the method with the proc() method from Y.But the method parameter is of type Z,why doesn't it call the overloaded method from the Z class?
It happens because you don't override the method 'proc' in Z class. When you overriding the method, you can't use argument, which has a child class of original argument class. If you add #Override on Z.proc(Z p), your code will be not compiled.
Let's imagine that it is possible, then you can use some method from Z class during executing Z.proc(Z p).
class Z extends Y {
public Z() {
v += 9;
}
public void proc(Z p) {
someActions();
System.out.println(39);
}
private void someActions() {
System.out.println("Some actions");
}
}
Now when you executing
X x = new Z();
x.proc(new X());
What should happens? There is no 'someActions' method in the X class. How it should works? That's why Z.proc(Z p) doesn't override X.proc(X p). Class Z, has two different methods: Z.proc(Z p) and Y.proc(X p).
When you calling
X x = new Z();
x.proc(new Z());
JVM looks for closest overrided or original method with signature 'proc(X)' to Z class (because X class has 'proc(X)' method) finds it in Y class and executing Y.proc(x p). That's why you see '57' in output.
Because you're passing an X to proc, so the proc for class Y prevails.
If you passed an actual Z declared as a Z, it would have printed 39.
Z x = new Z();
X y = new Z();
Z z = new Z();
z.proc(x); // prints 39
z.proc(y); // prints 57
Just to elaborate over Federico answer.
The "x" object is, in fact, a "X" variable that point to a "Z" instance in memory. "Z" instance has only two methods:
void proc(Z p)
void proc(X p)
But the runtime only is aware of the second method that is implemented at "X" class and its overridden by the method implemented in "Y" class.
So, when you call:
x.proc(z)
The runtime only knows about of this second method and call it, executing the overridden one.
The documentation says "An instance of InnerClass can exist only within an instance of OuterClass and has direct access to the methods and fields of its enclosing instance." This means with the instance of inner class, I can access the members of the outer class. But I am not able to do so.
public class TopLevel {
private int length;
private int breadth;
public class NonstaticNested{
private static final int var1 = 2;
public int nonStaticNestedMethod(){
System.out.println(var1);
length = 2;
breadth = 2;
return length * breadth;
}
}
public static void main(String[] args) {
TopLevel topLevel = new TopLevel();
NonstaticNested nonStaticNested = topLevel.new NonstaticNested();
// Trying to access the length variable on 'nonStaticNested' instance, but not able to do so.
}
}
I hope the comments within the main are self speaking.
public class A {
int a = 1;
public static void main(String[] args) {
B b = new B();
// Works as "a" is defined in "A"
System.out.println(b.a);
// Works as "b" is defined in "B"
System.out.println(b.b);
C c = new C();
C.D d = c.new D();
// Works as "c" is defined in "c"
System.out.println(c.c);
// Works as "d" is defined in "D"
System.out.println(d.d);
// Error here as there is no "c" defined within "D", it´s part of "C" and here´s your
// logical mistake mixing it somewhat with what inheritance provides (just my guess).
System.out.println(d.c);
}
}
class B extends A {
int b = 1;
}
class C {
int c = 1;
class D {
int d = 2;
public D() {
// Has access to "c" defined in C, but is not the owner.
c = 2;
}
}
}
private int a = 2;
public A(int x) {
a = x*2;
}
public A() {
this(5);
}
public int test() {
return a;
}
public static void main(String argv[]) {
A a1 = new A();
System.out.println(a1.test());
}
Hey guys, I'm new to Java and this is a question for my mock test. The output is 10, which I thought should be 5. Please help! Much appreciate!
You main invokes the A() constructor, which calls the A(int x) (by the statement this(5);). Therefore a is assigned 10 (a = x*2; where x is 5).
Well what happens is:
A a1 = new A();
this uses the public A() constructor so it goes to:
public A(){
this(5);
}
this will now call the public A(int x) constructor
and x will be equal to 5 so this will be called:
public A(5) {
a = 5 * 2;
}
Therefore:
a = 5 * 2;
a = 10;
So a will be 10.
So this:
System.out.println(a1.test());
Will call the test method on the a1 object, which returns the integer a of a1, which we found out is 10.
So essentially this happens:
System.out.println(10);
So the output is 10.
This is essentially what you will see if you use debug mode (which every IDE has).
I wanna change a variable's name by choice of user. I know that it can be done by Mab (not very charming), but I think that it can be done by polymorphism too, at least something that can simulate it. It is hard to explain, so the code below can illustrate it better. Thanks!
public class Main {
public static void main(String[] args) {
GenericObject o;
o = new Object1(10, 10);
o.wh();
System.out.println(o.w); // Output: 3 (ok)
System.out.println(o.h); // Output: 10 (ok)
o = new Object2(10, 10);
o.wh();
System.out.println(o.w); // Output: 7 (ok)
System.out.println(o.h); // Output: 4 (ok)
String inputFromUser = "1";
o = new Object + inputFromUser + (10, 10); /*I know that is an absurd, just to illustrate...
if polymorphism can solve this problem, I thik it's the best option. So how use it here?
I don't wanna use ifs or switchs, I will use more than 300 classes*/
o.wh();
System.out.println(o.w); // Output: 3 (that's what I wanna obtain)
System.out.println(o.h); // Output: 10 (that's what I wanna obtain)
}
}
abstract class GenericObject {
int w, h, x, y;
GenericObject (int x, int y) {
this.x = x;
this.y = y;
}
public abstract void wh();
}
class Object1 extends GenericObject{
Object1 (int x, int y) {
super(x, y);
}
#Override
public void wh () {
w = 3;
h = 10;
}
}
class Object2 extends GenericObject{
Object2 (int x, int y) {
super(x, y);
}
#Override
public void wh () {
w = 7;
h = 4;
}
}
Hope below code will help you.
HashMap<String, GenericObject > allTypes = new HashMap<>();
allTypes.put("1", new Object1(10, 10));
allTypes.put("2", new Object2(10, 10));
String inputFromUser = "1";
GenericObject o = allTypes.get(inputFromUser);
o.wh();
System.out.println(o.w); // Output: 3
System.out.println(o.h); // Output: 10
All design smells aside, I think that you're really looking for an answer using reflection. I think you can use the following code snippet to accomplish what you want:
// dynamically specify the class name based on the user's input.
Class<?> typeFromUser = Class.forName("Object" + inputFromUser);
// grab the correct package-private or public constructor whose type
// parameters are 2 primitive ints
java.lang.reflect.Constructor<?> constructor =
typeFromUser.getDeclaredConstructor(Integer.TYPE, Integer.TYPE);
// reflectively invoke the constructor with the two int values
Object obj = constructor.newInstance(10, 10);
// the instantiated object is of a raw type, cast it to the correct type
o = (GenericObject) obj;
I also tried this code and you can see the demo on IDEOne.
I think you can use reflection mechanism to do this. Below is the example code snippet:
String clsName = <your input(Object1 or Object2)>;
Class<?> clazz = Class.forName(clsName);
Constructor<?> cst = clazz.getDeclaredConstructor(int.class, int.class);
GenericObject obj = null;
if(clsName.equals("Object1")) {
obj = (Object1)cst.newInstance(10, 10);
} else if(clsName.equals("Object2")) {
obj = clsName.equals("Object1")
}
I got this task and I can't quite figure out how to solve it:
"Change all three of the x-variables related to the C-class."
class A {
public int x;
}
class B extends A {
public int x;
}
class C extends B {
public int x;
public void test() {
//There are two ways to put x in C from the method test():
x = 10;
this.x = 20;
//There are to ways to put x in B from the method test():
---- //Let's call this Bx1 for good measure.
---- //Bx2
//There is one way to put x in A from the method test();
---- //Ax1
}
}
To test, I set up this:
public class test {
public static void main(String[] args)
{
C c1=new C();
c1.test();
System.out.println(c1.x);
B b1=new B();
System.out.println(b1.x);
A a1=new A();
System.out.println(a1.x);
}
}
Which gives 20, 0, 0.
Now, I figured out I could write Bx1 like this:
super.x=10;
That would change the x in B, but I could not figure out how to call it in my test.java.
How do you get Bx1, Bx2, Ax1, and how do you call them for a test?
You can access the superclass's version of x by using a superclass type reference:
System.out.println("A's x is " + ((A)this).x);
That will get A#x.
But in general, it's a very bad idea to shadow a superclass's public instance members.
Example: (live copy on IDEOne)
class Example
{
public static void main (String[] args) throws java.lang.Exception
{
new C().test();
}
}
class A {
public int x = 1;
}
class B extends A {
public int x = 2;
}
class C extends B {
public int x = 3;
public void test() {
//There are two ways to put x in C from the method test():
System.out.println("(Before) A.x = " + ((A)this).x);
System.out.println("(Before) B.x = " + ((B)this).x);
System.out.println("(Before) C.x = " + this.x);
((A)this).x = 4;
System.out.println("(After) A.x = " + ((A)this).x);
System.out.println("(After) B.x = " + ((B)this).x);
System.out.println("(After) C.x = " + this.x);
}
}
Output:
(Before) A.x = 1
(Before) B.x = 2
(Before) C.x = 3
(After) A.x = 4
(After) B.x = 2
(After) C.x = 3
this is how your test method could look like
void test() {
this.x = 30;
A a = this;
a.x = 10;
B b = this;
b.x = 20;
}
It´s important to note, that you are accessing the variable of the Type of the class that you defined, so in that case you would Access, x from A, and x from B by defining a variable due to the this keyword.
Using getters and setters
class A {
public int x;
}
class B extends A {
public int x;
public void setAx(int x) {
super.x = x;
}
public int getAx() {
return super.x;
}
}
class C extends B {
public int x;
public void test() {
x = 10;
this.x = 20;
}
public void setBx(int x){
super.x = x;
}
public int getBx() {
return super.x;
}
public static void main(String[] args)
{
C c1= new C();
c1.x = 1;
c1.setAx(2);
c1.setBx(3);
System.out.println(c1.getAx()+"/"+c1.getBx()+"/"+c1.x);
}
}