File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "overriding" Watch "overriding" New topic
Author

overriding

challa
Greenhorn

Joined: Mar 28, 2005
Posts: 23
package inheritance;

class B {
String str = "Parent";
static void print() {
System.out.println("Parent Class");
}
void exec() {
print();
System.out.println(str);
}
}


public class Acls extends B {
String str = "Child";
static void print() {
System.out.println("Child Class");
}
public static void main(String[] args) {
Acls a = new Acls();
a.exec();
B b = new Acls();
b.exec();
}
}

the ouput is parent class
parent
parent class
parent

can anyone explain the above code clearly
Kalyani Marathe
Ranch Hand

Joined: Apr 06, 2005
Posts: 72
Yours is the case of static method. Static methods are not overriden so you get those outputs

When you call a.exec() as Acls doesn't have exec it will call the exec() in parent and print() call in exec will also be called from B as call from parent cannot go back to child. For the second case you are assigning child to parent and calling exec() and same way it works.

I hope this is correct.

Thanks.
challa
Greenhorn

Joined: Mar 28, 2005
Posts: 23
kalyani,
Iam sorry i didnt get you.Moreover what about the fields why it is printing parent in both the cases.

can anyone please explain me the above code.
vidya sagar
Ranch Hand

Joined: Mar 02, 2005
Posts: 580
HI Purnima

When derived class object is assign to base class references....

Variables and Static method use references so the base class variables and methods are displayed.Because it is resolved at compile time.

if public methods R in ur program then it use objects so derived class methods are called.Because it is known in run time only.

Hope uR clear now.....
challa
Greenhorn

Joined: Mar 28, 2005
Posts: 23
sagar,

In the code we are calling a.exec(); ,here a is a reference of subclass only then why it is printing parent.

anyone please explain.

Purnima.
vidya sagar
Ranch Hand

Joined: Mar 02, 2005
Posts: 580
Hi Purnima

Since we call exec() method, which is not overridden in derived class. So copy of that method will be available to dervied class.In which, call to print method is changed by compiler as super.print() while inheriting. therfore base class method is called

I hope u r clear now
vidya sagar
Ranch Hand

Joined: Mar 02, 2005
Posts: 580
Hi purnima

This is applicable only in the case of call to static methods
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: overriding
 
Similar Threads
Access control
init blocks example
Difference between Hidden and overriden methods.
Overriding/overloading
Inheritance