According to java 7 it is mentioned that we can create derived class instance using base class.
but
its not working i am trying to implement this concept
so that i am mention my code over here...
please provide me the solution and solve the problem....
this is the error
class A
{
public void show()
{
System.out.println("A class");
}
}
class B extends A
{
public void display()
{
System.out.println("B class");
}
}
class Demo
{
public static void main(String args[])
{
B obj=new B();
obj.display();
}
}
If obj is of type B, as in your posted code, it can't give you an error, since B contains the method display.
However, based on the error message in your comment - method display() location: variable obj of type A - the actual code is probably:
A obj=new B();
obj.display();
It fails to compile since the compiler determines which methods can be called by the compile time type of obj, which is A. Since A has no display method, you can't call it unless you cast obj to B explicitly:
A obj=new B();
((B)obj).display();
check your file name. make sure that the name of your file is Demo.java... Because when I Compile and run your code, it works. try also to check your java path.
Related
What is the real time example of dynamic polymorphism in java?
I have been asked so many places this question in interview
but dint got real answer. Code:
class A {
public void m1() {}
}
class B extends A {
public void m1() {}
}
class manage {
A a1 = new A();
B b1 = new B();
A a2 = new B();
//when i will call A's m1 it will call m1 of A
a1.m1();
//when i will call B's m1 it will call m1 of B
b1.m1();
//when i will call B's m1
a2.m1();
}
in the above code by looking , i can say its whose object will be called then why its run time polymorphism
Anyone can please help the real time correct example of runtime/dynamic polymorphism ??
Lets change your code example just a little bit. Instead of having a test class that defines the objects to test, we only offer a method taking some arguments:
public void testCalls(A a1, A b1, A b2) {
a1.m1();
...
Now, can you still say what will happen? "Hmm, that will depend on what gets passed to the method call?!"
In your example, you know what is going to happen because you can easily deduct the true nature of all objects. But what if you don't have that information? When you are only providing an interface, and the incoming objects aren't showing up in your source code?!
Thus: what matters is the true type of an object at runtime. Of course, when you construct a simple example, you always know that true type. But the things that matter in the real world are simply not that simple.
"Dynamic polymorphism is the polymorphism existed at run-time".
That mean Java compiler does not understand which method is called at compilation time. Only JVM decides which method is called at run-time.
In your example, the compiler don't know the behavior of a2.m1(). However, at the runtime, the JVM will invoke the code which was defined in the class B.
class A {
public void m1(){
System.out.println("Inside A's m1 method");
}
}
class B extends A {
// overriding m1()
public void m1(){
System.out.println("Inside B's m1 method");
}
}
class C extends A {
public void m1(){
System.out.println("Inside C's m1 method");
}
}
// Driver class
class Dispatch {
public static void main(String args[]) {
// object of type A
A a = new A();
a.m1(); // calling m1 of A
a = new B();
a.m1(); // calling m1 of B
a = new C();
a.m1(); // calling m1 of C
}
}
Results:
Inside A's m1 method
Inside B's m1 method
Inside C's m1 method
As the name suggests, it happens in realtime aka runtime.
Say I have the following code
public class A {
public void callme() {
System.out.println("Calling of class A function ");
}
}
public class B extends A {
public void callme() {
System.out.println(" Calling of class B fuction ");
}
public void Hello() {
System.out.println("hello guys");
}
}
and a main() that does the following
public class Main {
public static void main(String [] args){
A a = new B();
B b = new B();
b = (B)a;
a.callme();
b.callme();
a.Hello(); // show error : Hello is undefined for method A
}
}
The book says "you get the behavior associated with the object to which the variable refers at runtime". Ok, I get behavior of B class when a method callme is called, but when I access the method Hello, it shows an error that Hello is undefined for method A. why is that?
Polymorphism doesn't work this way. Since A is parent of B, B can inherit methods of A (like son can inherit properties of father), but its not vice versa because A doesn't know which classes are inheriting it (A does not know who are its children.)
For Example, suppose there is one more class C:
public class C extends A {
public void callme(){
System.out.println(" Calling of class C fuction ");
}
public void Hello(){
System.out.println("hello guys, I am C");
}
}
Now, if you use
a.Hello();
how will a know which child class it should call since it does not methods of its child. only its own abstract method, which it knows child will implement for sure.
a is of type A, even if it is referring to an instance of B.
A doesn't have the Hello method (even an abstract declaration). So your compiler emits the error. Adjusting your code slightly to
public abstract class A {
public abstract void Hello();
/*the rest as before*/
would be a fix. A is then assuming the characteristics of an interface.
public class B extends A {
public void callme(){
System.out.println(" Calling of class B fuction ");
}
public void Hello(){ // hello method is only the part of class B not A.
System.out.println("hello guys");
}
}
In above class hello() method is a part of B only. it not override by the method of A.
now in your main method call
public static void main(String [] args){
A a= new B(); // object of b referred by (a) Reference Variable of A
B b= new B(); // object of b referred by (b) Reference Variable of B
b= (B)a;
a.callme(); //override takes place and method of B's Callme() called
b.callme(); //again override takes place here and method of B's Callme() called
a.Hello();// buttttttt
b.Hello(); // this will compile and executes fine.
}
}
Here you used the reference variable of class A which don't have any method name Hello(). So, Method Resolution will not take place(won't be able to find any method like Hello()).
but if you try to call b.Hello() using the reference variable of B then it will work fine to you.
Now suppose there is another class C which is a sub class of A and contains a Method Name Hello().
public class C extends A {
public void Hello(){ // hello method is only the part of class B not A.
System.out.println("hello guys");
}
}
In main a Statement like this
A a = new C();
and if you try to call a.Hello() then which Hello() method will call. Compiler will get confused.
So, This concept work only when you try to override the method of super class in sub Class.
Is the parent class aware of classes derived from it ?
Casting does not change the actual object type. Only the reference type gets changed.
I highly recommend you my upcasting and downcasting writing from the link
Say we have the class
package myTest;
public class a {
public static void main(String[] args) {
b printToConsole = new b();
}
}
which I cannot modify. I also have the class
package myTest;
public class b {
public static void printThis() {
System.out.println("this is a test");
}
}
which I can modify. I want to call a (which I cannot modify) and somehow print to the console "this is a test". With the current classes, this obviously does not work and I understand why.
Summary:
Is there a way, without modifying a, to call a and have "this is test" to the console? (b can be modified).
You could either call the print statement in the constructor of b
public b() {
System.out.println("this is a test");
}
or from a static initializer
static {
System.out.println("this is a test");
}
(The second will only produce output for the first object created)
Put System.out.println("this is a test"); in the default/no-arg constructor of b:
public class b {
public b() {
System.out.println("this is a test");
}
}
With the current classes, this obviously does not work and I understand why.
Because the printThis method of class b is not called anywhere in class a, so it doesn't get executed. Methods don't run automatically somehow, they have to be called. You'd have to call the method from class a:
b printToConsole = new b();
printToConsole.printThis();
Or you would have to put the content of the printToConsole method in the constructor of class b (class a would not have to be modified then). The constructor is called when a new instance of b is created (the new b(); statement in class a):
public class b {
// Constructor
public b() {
System.out.println("this is a test");
}
}
Yes you can do it in many ways:-
1st way using constructor
class B
{
public B()
{
System.out.println("This is a test");
}
}
2nd way using anonymous block
class B
{
{
System.out.println("This is a test");
}
}
3rd one is by using static block
class B
{
static{
System.out.println("This is a test");
}
}
Actually there is priorities of execution of these block if these are stated in a single class as follow:-
1.Static Block
2.Init Block(Anonymous Block)
3.Constructor
These all 3 blocks execute at runtime with object initialization.
basically compiler copy the init block to the constructor and it is used for share codes between multiple constructors.
Ok! I have same code written in Java and C# but the output is different!
class A
{
public void print()
{
Console.WriteLine("Class A");
}
}
class B : A
{
public void print()
{
Console.WriteLine("Class B");
}
}
class Program
{
static void Main(string[] args)
{
A a = new B();
a.print();
Console.Read();
}
}
Output: Class A. It is in C#.
But when same code was ran in Java, the output was Class B. Here is the Java Code:
class A
{
public void print()
{
System.out.println("Class A");
}
}
class B extends A
{
public void print()
{
System.out.println("Class B");
}
}
public class Program{
public static void main(String []args){
A a = new B();
a.print();
}
}
So, why this is showing different results? I do know that, in Java, all methods are virtual by default that's why Java outputs Class B.
Another thing is that, both languages claim that they are emerged or inspired by C++ then why they are showing different results while both have same base language(Say).
And what does this line A a = new B(); actually doing? Isn't a holding object of class B? If it is so, then why C# displays Class A and Java shows Class B?
NOTE This question was asked in interview with the same code provided above. And I answered with output Class B (with respect to Java) but he said Class A will be right output.
Thank you!
This is because in C# methods of derived classes hide, not override, methods of their base class. The methods that you would like to override need to be explicitly marked with the keyword virtual in the base, and with the keyword override in the derived classes.
In contrast, in Java all methods are virtual by default: simply specifying the same signature is sufficient for an override.
Here is how to make your C# program an equivalent of Java program:
class A
{
public virtual void print() // Add "virtual"
{
Console.WriteLine("Class A");
}
}
class B : A
{
public override void print()// Add "override"
{
Console.WriteLine("Class B");
}
}
After A a = new B(), variable a is holding object of B but the output is "Class A"! Shouldn't it call method of class B?
When you hide a method, rather than overriding it, your derived class keeps both methods - the one in the base class, and the one in the derived class. Both these methods remain accessible to the outside callers. They can decide which of the two methods to call by using an object of an appropriate static type. Here is an example:
B b = new B();
b.print(); // Prints "Class B"
((A)b).print(); // Prints "Class A"
Demo on ideone.
When you use virtual/override, you can access only one method from the outside - namely, the one in the derived class. The method in the base class can be accessed by methods of the derived class, but not by the outside users of the derived class.
In Java, non-static methods are virtual, whereas in C#, they are not. You will need to use the virtual and override keywords on your print method to get the same behaviour in c#.
Polymorphic behaviour in C#:
class A
{
public virtual void print()
{
Console.WriteLine("Class A");
}
}
class B : A
{
public override void print()
{
Console.WriteLine("Class B");
}
}
Edit
Getting back to your original C# code, you will get a compile time warning on B.print when you use the same method signature in both a subclass and its superclass, viz:
The keyword 'new' is required on 'print' because it hides method
'MyNamespace.A.print()'
This is a good indication that the method won't be called polymorphically / virtually. To avoid the warning (and retain your original C# behaviour), in B you would need to add new:
public new void print()
Simple java code snippet. It has three classes. After compiling the code please delete A.class and then execute the code. Code still runs, why its not checking whether the byte code of A exists or not?
class A {
static {
System.out.println("In the class A");
}
public A() {
}
}
class B {
private A a = null;
static {
System.out.println("In the class B");
}
public B() {
a = new A();
}
}
public class ExampleLinkage {
static {
System.out.println("In the class A");
}
public ExampleLinkage(String str) {
}
public static void main(String args[]) {
try {
System.out.println("In the main method of ExampleLinkage");
Class.forName("com.bt.rtti.B");
} catch(Exception e) {
e.printStackTrace();
}
}
}
I would guess that at no point the class A is needed to be loaded, even though there is an instance of it inside B, since you never instantiate an instance of B.
the JVM is very lazy when it load classes. it loads them either when you instantiate an object of that class (at the first time), when you explicitly load a class with Class.forName() or when you otherwise reference the class in a way that requires information from it (try accessing a static member of A from the static initializer of B and see that A will get loaded.
As your not recompiling it, just running the class.
Class A is not used in the code (i.e. in the main method).
At run-time classes are loaded as they are being used. At that time, you would get a ClassNotFoundError. But if you are not using the class, there is not need for it to be there.
Try to make an instance of B (which needs an instance of A), then you will get an error.
Further to Gordon's answer, you are only running the class, and class A is not required, if you called A's constructor or referenced a static field or method in A, then you would get the ClassNotFoundException you are expecting