Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Overriding problem  RSS feed

 
Aravind Jerubandi
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Java Ranchers,
first of all, HAPPY NEW YEAR to all...
I have seen the following question in this forum, some time back. But, when i read about this topic i got one doubt.
CODE:
public class test
{
public static void main(String args[])
{
Derived d = new Derived();
}
}
class Base{
Base(){
print();
}
void print(){
System.out.println("in Base Class");
}
}
class Derived extends Base{
String temp = "temp";
void print(){
System.out.println("in Drived Class "+temp);
}
}

The output for this code is : "in Drived Class null"
Now i have read that, the instance variables and the instance methods can not be accessed, until the super constructor is completed. So, the value of the string is 'null' which can not be accessed until, the 'Base' constructor is completed. But then, how come the method 'print' in Derived class is accessible, even before the completion of 'Base' constructor.

Thanks in advance,
James.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by James Richy:
Now i have read that, the instance variables and the instance methods can not be accessed, until the super constructor is completed.


Well, that's simply not true. They *can* be accessed, but it's typically something you want to avoid, because the instance variables aren't *initialized* until the super constrcutor is completed.
 
Aravind Jerubandi
Ranch Hand
Posts: 49
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks a lot Ilja.
 
Mr. C Lamont Gilbert
Ranch Hand
Posts: 1170
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Never call overridable methods from derived classes in the constructor. Accident waiting to happen. Though you will find this is done a lot in the world of Java. It always ends badly.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!