How does this object get created? - java

Many articles say objects get created only after the class's constructor gets called. But I found this snippet and it works fine.
public class A {
public A(){
this.foo();//line #1
}
private void foo() {
System.out.print("without an instance..!!!!");
}
}
class B extends A
{
public static void main(String[] args){
A a = new A(); //line #2
}
}
Here you see, I'm trying to create an object of its super class in line #2 and in its constructor how come its method got called without an instance. What's going on here, is Constructer of instance of A is getting called here.?

The constructor is always called when an object is created. Even if you don't explicitly define a constructor, the compiler will generate one for you with an empty body.
You may call other methods of the class from the constructor. All non-static methods get an implicit (compiler generated) parameter to this, the actual class instance. However, it is important to know that while executing the constructor, the object is not yet fully created, although all data members of the class in question (if there are such) have already been initialized, at least to some default value. Because of this, you
should not publish this (i.e. pass it to other objects / threads) before exiting the constructor call, and
you should not call non-final, non-private methods from the constructor.
Doing either of these (in a non-final class) means that you give access to an object not yet fully constructed, which may result in subtle, hard to find bugs later. E.g. if the virtual method in question is overridden in a subclass and the implementation depends on some member defined and initialized only in the subclass constructor, the method gets called before the subclass member is correctly initialized, thus it won't have the value you would expect.

Because public static void main is the entry point of the programm. So you do not require to create instance of the class B.
The method signature for the main() method contains three modifiers:
* public indicates that the main() method can be called by any object.
* static indicates that the main() method is a class method.
* void indicates that the main() method has no return value.
Read more : Understanding public static void main function
So that Constructor of A is get called when the programm get executed and that it calls the foo method of the super class A.

It's not called without an instance.
You call it on this - that's an instance.

The constructor of A is getting called because you called it directly. However, if you wished to call A through B, within Main [which is called without a current instance of the containing class B (1 because its static, and 2. its reserved for the beginning of the application)] you would just change the "new A()" to "new B()"
Since you're using a constructor with no parameters, a default constructor in automatically generated at compile time.

Whether main() is the entry point or not is not the explanation. The reason is that main() is static, therefore doesn't require an instance of its class.
No instance of B is ever created by this program.

class A is public, and its inherited by class B. class B can instantiate class A, with
A object=new A()
and the object initialization is done by Constructor method defined automatically. Constructor of A in turn calls method foo(), which is private to class A. As far as i know, to call a method from a class which is in the same class scope, no instance is needed.

Related

Can I use a non-static method in another non static method? [duplicate]

I was just reading over the text given to me in my textbook and I'm not really sure I understand what it is saying. It's basically telling me that static methods or class methods include the "modifier" keyword static. But I don't really know what that means?
Could someone please explain to me in really simple terms what Static or Class Methods are?
Also, could I get a simple explanation on what Instance methods are?
This is what they give me in the textbook:
There are important practical implications of the presence or absence of the static modifier. A public class method may be invoked and executed as soon as Java processes the definition of the class to which it belongs. That is not the case for an instance method. Before a public instance method may be invoked and executed, an instance must be created of the class to which it belongs. To use a public class method, you just need the class. On the other hand, before you can use a public instance method you must have an instance of the class.
The manner in which a static method is invoked within the definition of another method varies according to whether or not the two methods belong to the same class. In the example above, factorial and main are both methods of the MainClass class. As a result, the invocation of factorial in the definition of main simply references the method name, "factorial".
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.
However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.
You can do this to execute a static method:
MyClass.staticMethod(); // Simply refers to the class's static code
But to execute a non-static method, you must do this:
MyClass obj = new MyClass(); //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code
On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)
for example:
Person.staticMethod(); //accessing static method.
for non-static method you must instantiate the class.
Person person1 = new Person(); //instantiating
person1.nonStaticMethod(); //accessing non-static method.
Difference between Static methods and Instance methods
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call.
Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'.
Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
If state of a method is not supposed to be changed or its not going to use any instance variables.
You want to call method without instance.
If it only works on arguments provided to it.
Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.
The behavior of an object depends on the variables and the methods of that class. When we create a class we create an object for it. For static methods, we don't require them as static methods means all the objects will have the same copy so there is no need of an object.
e.g:
Myclass.get();
In instance method each object will have different behaviour so they have to call the method using the object instance.
e.g:
Myclass x = new Myclass();
x.get();
Static Methods vs Instance methods
Constructor:
const Person = function (birthYear) {
this.birthYear = birthYear;
}
Instance Method -> Available
Person.prototype.calcAge = function () {
2037 - this.birthYear);
}
Static Method -> Not available
Person.hey = function(){
console.log('Hey')
}
Class:
class PersonCl {
constructor(birthYear) {
this.birthYear = birthYear;
}
/**
* Instance Method -> Available to instances
*/
calcAge() {
console.log(2037 - this.birthYear);
}
/**
* Static method -> Not available to instances
*/
static hey() {
console.log('Static HEY ! ');
}
}
The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :)
Same is the case with variables.

Does invoking a constructor mean creating object?

When we create a Subclass object which extends an abstract class, the abstract class constructor also runs . But we know we cannot create objects of an abstract class. Hence does it mean that even if a constructor completes running without any exception, there is no guarantee whether an object is created?
Hence does it mean that even if a constructor completes running
without any exception, there is no guarantee whether an object is
created?
Simply speaking, a constructor does not create an object. It just initializes the state of the object. It's the new operator which creates the object. Now, let's understand this in little detail.
When you create an object using statement like this:
new MyClass();
The object is first created by the new operator. Just before a reference to the newly created object is returned as the result, the indicated constructor is processed to initialize the new object.
Now consider the case of Abstract class and it's concrete SubClass, when you do like this:
AbstractClass obj = new ConcreteClass();
new operator creates an object of ConcreteClass, and invokes its constructor to initialize the state of the created object. In this process, the constructor of the abstract class is also called from the ConcreteClass constructor, to initialize the state of the object in the abstract class.
So, basically the object of AbstractClass is not created. It's just that it's constructor is invoked to initialize the state of the object.
Lessons Learnt:
The object is created by new operator, and not by the invocation of the constructor itself. So, the object is already created before any constructor is invoked.
Constructor is just used to initialize the state of the object created. It does not create an object itself.
An object state can also be contained in an abstract super class.
So, the purpose of invocation of Abstract class constructor, is only to initialize the object completely, and no object is created in process.
See:
Creation of new Class Instance - JLS-Section#12.5
But we know we cannot create objects of an Abstract class
Right but JVM can.
does it mean that even if a constructor completes running without any exception , there is no guarantee whether an object is created ?
The object is definitely created internally.
Does invoking a constructor mean creating object?
Not always. you can invoke constructor using super() and this() but it won't instantiate an object. (but will just invoke the constructor)
class AClass
{
AClass()
{
this(1); // will invoke constructor, but no object instatiated.
}
AClass(int a)
{
}
public static void main(String[] args)
{
AClass obj = new AClass(); // one object instantiated.
}
}
Barring any exceptions, the abstract class constructor is only run from within the subclass's constructor (as the first statement). Therefore you can be sure that every time a constructor is run, it is in the process of creating an object.
That said, you may call more than one constructor in the process of creating a single object, such as Subclass() calling Subclass(String) which calls AbstractClass via a super()call, and so forth.
Subclass == BaseClass + Extras you add in sub class
Thus when you create a subclass by calling its constructor, there is a call to base class constructor as well to make sure that all attributes (of the base class) are also properly initialized.
You can only call the abstract class constructor as a part of a concrete subclass constructor. This is OK, since the abstract class is extended into a concrete class and it is an object of that concrete class that is being created.
When you invoke a constructor using new, a new object is being created.
Now, as you probably already know, every constructor of any subclass, either implicitly or explicitly, directly or indirectly, invokes a constructor from the parent class (which, in turns, invokes one from its own parent class, all the way up to object). This is called constructor chaining.
The above, however doesn't mean that multiple objects are created. The object has been created at the new call and all constructors working on that object are already handed an allocated area. Therefore, constructor chaining does not create new objects. One call to new will return you one object.
This is how the flow works when you invoke the constructor of your subclass:
Constructor of Abstract class runs --> the object is half initialized here.
Constructor of subclass finishes execution --> The object is fully initialized and hence completely created here.
I am completely disagree that the object for an abstract class can not be created and only jvm can does it in case of Inheritance even a programmer can do it a t times whenever or wherever he/she intends to do so by using the concept of anonymous class:
Look at this code and try it by your Own
abstract class Amit{
void hai()
{System.out.print("Just Wanna say Hai");}
abstract void hello();
}
class Main{
stic public void main(String[]amit)
{
Amit aa=new Amit(){
void hello(){Sstem.out.print("I actually dont say hello to everyone");
}};
aa.hello(); }}

Difference between Static methods and Instance methods

I was just reading over the text given to me in my textbook and I'm not really sure I understand what it is saying. It's basically telling me that static methods or class methods include the "modifier" keyword static. But I don't really know what that means?
Could someone please explain to me in really simple terms what Static or Class Methods are?
Also, could I get a simple explanation on what Instance methods are?
This is what they give me in the textbook:
There are important practical implications of the presence or absence of the static modifier. A public class method may be invoked and executed as soon as Java processes the definition of the class to which it belongs. That is not the case for an instance method. Before a public instance method may be invoked and executed, an instance must be created of the class to which it belongs. To use a public class method, you just need the class. On the other hand, before you can use a public instance method you must have an instance of the class.
The manner in which a static method is invoked within the definition of another method varies according to whether or not the two methods belong to the same class. In the example above, factorial and main are both methods of the MainClass class. As a result, the invocation of factorial in the definition of main simply references the method name, "factorial".
The basic paradigm in Java is that you write classes, and that those classes are instantiated. Instantiated objects (an instance of a class) have attributes associated with them (member variables) that affect their behavior; when the instance has its method executed it will refer to these variables.
However, all objects of a particular type might have behavior that is not dependent at all on member variables; these methods are best made static. By being static, no instance of the class is required to run the method.
You can do this to execute a static method:
MyClass.staticMethod(); // Simply refers to the class's static code
But to execute a non-static method, you must do this:
MyClass obj = new MyClass(); //Create an instance
obj.nonstaticMethod(); // Refer to the instance's class's code
On a deeper level the compiler, when it puts a class together, collects pointers to methods and attaches them to the class. When those methods are executed it follows the pointers and executes the code at the far end. If a class is instantiated, the created object contains a pointer to the "virtual method table", which points to the methods to be called for that particular class in the inheritance hierarchy. However, if the method is static, no "virtual method table" is needed: all calls to that method go to the exact same place in memory to execute the exact same code. For that reason, in high-performance systems it's better to use a static method if you are not reliant on instance variables.
Methods and variables that are not declared as static are known as instance methods and instance variables. To refer to instance methods and variables, you must instantiate the class first means you should create an object of that class first.For static you don't need to instantiate the class u can access the methods and variables with the class name using period sign which is in (.)
for example:
Person.staticMethod(); //accessing static method.
for non-static method you must instantiate the class.
Person person1 = new Person(); //instantiating
person1.nonStaticMethod(); //accessing non-static method.
Difference between Static methods and Instance methods
Instance method are methods which require an object of its class to be created before it can be called. Static methods are the methods in Java that can be called without creating an object of class.
Static method is declared with static keyword. Instance method is not with static keyword.
Static method means which will exist as a single copy for a class. But instance methods exist as multiple copies depending on the number of instances created for that class.
Static methods can be invoked by using class reference. Instance or non static methods are invoked by using object reference.
Static methods can’t access instance methods and instance variables directly. Instance method can access static variables and static methods directly.
Reference : geeksforgeeks
Static methods, variables belongs to the whole class, not just an object instance. A static method, variable is associated with the class as a whole rather than with specific instances of a class. Each object will share a common copy of the static methods, variables. There is only one copy per class, no matter how many objects are created from it.
Instance methods => invoked on specific instance of a specific class. Method wants to know upon which class it was invoked. The way it happens there is a invisible parameter called 'this'. Inside of 'this' we have members of instance class already set with values. 'This' is not a variable. It's a value, you cannot change it and the value is reference to the receiver of the call.
Ex: You call repairmen(instance method) to fix your TV(actual program). He comes with tools('this' parameter). He comes with specific tools needed for fixing TV and he can fix other things also.
In static methods => there is no such thing as 'this'.
Ex: The same repairman (static method). When you call him you have to specify which repairman to call(like electrician). And he will come and fix your TV only. But, he doesn't have tools to fix other things (there is no 'this' parameter).
Static methods are usually useful for operations that don't require any data from an instance of the class (from 'this') and can perform their intended purpose solely using their arguments.
In short, static methods and static variables are class level where as instance methods and instance variables are instance or object level.
This means whenever a instance or object (using new ClassName()) is created, this object will retain its own copy of instace variables. If you have five different objects of same class, you will have five different copies of the instance variables. But the static variables and methods will be the same for all those five objects. If you need something common to be used by each object created make it static. If you need a method which won't need object specific data to work, make it static. The static method will only work with static variable or will return data on the basis of passed arguments.
class A {
int a;
int b;
public void setParameters(int a, int b){
this.a = a;
this.b = b;
}
public int add(){
return this.a + this.b;
}
public static returnSum(int s1, int s2){
return (s1 + s2);
}
}
In the above example, when you call add() as:
A objA = new A();
objA.setParameters(1,2); //since it is instance method, call it using object
objA.add(); // returns 3
B objB = new B();
objB.setParameters(3,2);
objB.add(); // returns 5
//calling static method
// since it is a class level method, you can call it using class itself
A.returnSum(4,6); //returns 10
class B{
int s=8;
int t = 8;
public addition(int s,int t){
A.returnSum(s,t);//returns 16
}
}
In first class, add() will return the sum of data passed by a specific object. But the static method can be used to get the sum from any class not independent if any specific instance or object. Hence, for generic methods which only need arguments to work can be made static to keep it all DRY.
If state of a method is not supposed to be changed or its not going to use any instance variables.
You want to call method without instance.
If it only works on arguments provided to it.
Utility functions are good instance of static methods. i.e math.pow(), this function is not going to change the state for different values. So it is static.
The behavior of an object depends on the variables and the methods of that class. When we create a class we create an object for it. For static methods, we don't require them as static methods means all the objects will have the same copy so there is no need of an object.
e.g:
Myclass.get();
In instance method each object will have different behaviour so they have to call the method using the object instance.
e.g:
Myclass x = new Myclass();
x.get();
Static Methods vs Instance methods
Constructor:
const Person = function (birthYear) {
this.birthYear = birthYear;
}
Instance Method -> Available
Person.prototype.calcAge = function () {
2037 - this.birthYear);
}
Static Method -> Not available
Person.hey = function(){
console.log('Hey')
}
Class:
class PersonCl {
constructor(birthYear) {
this.birthYear = birthYear;
}
/**
* Instance Method -> Available to instances
*/
calcAge() {
console.log(2037 - this.birthYear);
}
/**
* Static method -> Not available to instances
*/
static hey() {
console.log('Static HEY ! ');
}
}
The static modifier when placed in front of a function implies that only one copy of that function exists. If the static modifier is not placed in front of the function then with every object or instance of that class a new copy of that function is made. :)
Same is the case with variables.

Why can a Java static method call a constructor, but not refer to this?

My Assumptions:
Static method cannot cannot call non-static methods.
Constructors are kind of a method with no return type.
Given this example...
public class Main {
public static void main(String[] args) {
Main p = new Main(); // constructor call
k(); // [implicit] `this` reference
}
protected Main() {
System.out.print("1234");
}
protected void k() {
}
}
this line prints 1234: Main p = new Main()
this line throws an Exception: k()
Why did the example code do those two things? Don't they conflict with my above Assumptions? Are my Assumptions correct?
1 - Static method cannot cannot call non-static methods.
Sure they can, but they need an object to call the method on.
In a static method, there's no this reference available, so foo() (which is equivalent to this.foo()) is illegal.
2 - Constructors are kind of a method with no return type.
If they should be compared to methods, I would say constructors are closer to non-static methods (since there is indeed a this reference inside a constructor).
Given this view, it should be clear to you why a static method can call a constructor without any problems.
So, to sum it up:
Main p = new Main();
is okay, since new Main() does not rely on any existing object.
k();
is not okay since it is equivalent to this.k() and this is not available in your (static) main method.
No. Constructors aren't ordinary methods in this respect. The whole point of the constructor is to, well, construct a new instance of the class.
So it can be invoked in static scope too. Just think about it: if you needed an existing instance of your class in order to create a new instance of it, you would simply never be able to instantiate it ever.
A few clarifications:
Static method cannot cannot call non-static methods.
Not quite. You can call a nonstatic method from inside a static method, just you need to scope it to a specific object of that class. I.e.
p.k();
would work perfectly in your code sample above.
The call
k();
would be fine inside an instance (nonstatic) method. And it would be equivalent to
this.k();
The implied this refers to the current instance of the class. Whenever the compiler sees an unqualified call like k() within an instance method, it will automatically scope it with this. . However, since static methods aren't tied to any instance of the class, you (and the compiler) can't refer to this inside a static method. Hence you need to explicitly name an instance of the class to call an instance method on.
Rules are simple:
1 - Static method cannot cannot call non-static methods.
That's simply not true. A static method can call a non-static method, just via a "target" reference. For example, this is fine in a static method:
Integer x = Integer.valueOf(10);
int y = x.intValue(); // Instance method!
The real point is "there's no this reference within a static method".
2 - Constructors are kind of a method with no return type.
That's not a really useful model, to be honest. It makes more sense (from the caller's point of view) to consider a constructor as a static method with a return type that's the same as the declaring class, but even that's not a perfect model by any means.
I suggest you think of a constructor as a different type of member. Embrace the differences between constructors and methods, instead of trying to hide them.

A call to a static method within the parameter list of super() is valid in Java. Why?

Let's look at the following code snippet in Java.
package trickyjava;
class A
{
public A(String s)
{
System.out.println(s);
}
}
final class B extends A
{
public B()
{
super(method()); // Calling the following method first.
}
private static String method()
{
return "method invoked";
}
}
final public class Main
{
public static void main(String[] args)
{
B b = new B();
}
}
By convention, the super() constructor in Java must be the first statement in the relevant constructor body. In the above code, we are calling the static method in the super() constructor parameter list itself super(method());.
It means that in the call to super in the constructor B(), a method is being
called BEFORE the call to super is made! This should be forbidden by the compiler but it works nice. This is somewhat equivalent to the following statements.
String s = method();
super(s);
However, it's illegal causing a compile-time error indicating that "call to super must be first statement in constructor". Why? and why it's equivalent super(method()); is valid and the compiler doesn't complain any more?
The key thing here is the static modifier. Static methods are tied to the class, instance methods (normal methods) are tied to an object (class instance). The constructor initializes an object from a class, therefore the class must already have been fully loaded. It is therefore no problem to call a static method as part of the constructor.
The sequence of events to load a class and create an object is like this:
load class
initialize static variables
create object
initialize object <-- with constructor
object is now ready for use
(simplified*)
By the time the object constructor is called, the static methods and variables are available.
Think of the class and its static members as a blueprint for the objects of that class. You can only create the objects when the blueprint is already there.
The constructor is also called the initializer. If you throw an exception from a constructor and print the stack trace, you'll notice it's called <init> in the stack frame. Instance methods can only be called after an object has been constructed. It is not possible to use an instance method as the parameter for the super(...) call in your constructor.
If you create multiple objects of the same class, steps 1 and 2 happen only once.
(*static initializers and instance initializers left out for clarity)
Yep, checking the JVM spec (though admittedly an old one):
In the instance init method, no reference to "this" (including the implicit reference of a return) may occur before a call to either another init method in the same class or an init method in the superclass has occurred.
This is really the only real restriction, so far as I can see.
The aim of requiring the super constructor to be invoked first is to ensure that the "super object" is fully initialized before it is used (It falls short of actually enforcing this because the super constructor can leak this, but that's another matter).
Calling a non-static method on this would allow the method to see uninitialized fields and is therefore forbidden. A static method can only see these fields if it is passed this as argument. Since accessing this and super is illegal in super constructor invocation expressions, and the call to super happens before the declaration of any variables that might point to this, allowing calls to static methods in super constructor invocation expressions is safe.
It is also useful, because it allows to compute the arguments to the super constructor in an arbitrarily complex manner. If calls to static methods weren't allowed, it would be impossible to use control flow statements in such a computation. Something as simple as:
class Sub extends Super {
Sub(Integer... ints) {
super(Arrays.asList(ints));
}
}
would be impossible.
This is one situation where the java syntax hides what's really going on, and C# makes it a bit clearer.
In C# your B would look like
class B : A {
public B() : base(method()) {
}
private static String method() {
return "method invoker";
}
}
Although the java syntax places super(method) within the constructor it's not really called there: All the parent initialization is run before your subclass constructor. The C# code shows this a little more clearly; by placing super(method()) at the first line of the java constructor you're simply telling java to use the parameterized constructor of the super class rather than the parameterless version; this way you can pass variables to the parent constructor and they'll be used in the initialization of the parent level fields before your child's constructor code runs.
The reason that super(method()) is valid (as the first line in a java constructor) is because method() is being loaded with the static elements--before the non-static ones, including the constructors--which allows it to be called not only before B(), but before A(String) as well. By saying
public B() {
String s = method();
super(s);
}
you're telling the java compiler to initialize the super object with the default constructor (because the call to super() isn't the first line) and you're ready to initialize the subclass, but the compiler then becomes confused when it sees that you're trying to initialize with super(String) after super() has already run.
A call to super is a must in java to allow the parent to get initalized before anything with child class starts.
In the case above, if java allows String s= method(); before the call to super, it opens up flood gate of things that can be done before a call to super. that would risk so many things, essentially that allows a half baked class to be used. Which is rightly not allowed. It would allow things like object state (some of which may belong to the parent) being modified before it was properly created.
In case of super(method()); call, we still adhere to the policy of completing parent initialization before child. and we can use a static member only, and static member of child classes are available before any child objects are created anyways. so the method is avilable and can be called.
OK..i think, this one could be relevant that, if we are calling some member with Super, then it first try to invoke in super class and if it doesn't find same one then it'll try to invoke the same in subclass.
PS: correct me if i'm wrong

Categories

Resources