I couldn't find information if it is possible to write public void in constructor section. Is it possible?
At the byte code level, a constructor is always void so it would be redundant to specify it. i.e. the constructor is always called <init>V i.e. the V is the return type where V == void. Similarly the static initialiser is <clinit>V You will see this notation if you take a stack trace (e.g. print an exception) while in these methods.
The constructor actually takes the object to be initialised as an argument as the object is created before calling the constructor. Note: you can create the object without calling a constructor with Unsafe.allocateInstance(Class)
I couldn't find information if it is possible to write public void in constructor section. Is it possible?
It is not possible to write it as Java distinguishes a constructor from a method is that it must have the same name as the class, and it must not specify a return type. If you specify a return type, it assumes it's a method.
The notation x = new Clazz() also limits the number of return values to 1 which is the object. There is no easy way to modify this notation to return more than one object. i.e. supporting a return type for constructors would not be easy.
If you want to define a return type, most likely you are thinking of a factor method like this.
public static MyInterface createObject() {
return new MyClass();
}
Note how the return type is different to the class actually created, but there is still only one reference returned.
The constructor syntax is defined in the Java Language Specification. Anything else is incorrect.
The question is unclear. Peter Lawrey answered one interpretation, this is an answer to another.
You cannot declare methods within a constructor. You can, however, declare a class and declare variables.
Because you are able to declare a class within a constructor, you could declare a method inside of a class and then use the class. If the method isn't static you can construct an object of the class.
No, Java only allows a method to be declared within a class, not within another method or constructor.Indirectly you can do something like this :
public A() {
class B {
public void m() {
}
}
}
Related
I have come across such a code and my Java knowledge is not enough for it - I am pretty sure it is
something simple, but I have not found an explanation as don't know how to express it in google.
Here is the abstracted code, I hope nothing is missing:
public class A{
Car car;
.
.
.
public A do() {
car.move(somewhere);
return this;
}
}
public class B{
protected A doSomething(final A a ){
a.do();
return a;
}
}
My first question is what does "return this;" mean here? http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html does not include such a case.
Second is how a.do() works in method doSomething()? Method do() is supposed to return a value, yet it is not assigned anywhere?
Lastly, I suppose that "a" returned from doSomething() was changed in this method. Is this allowed, as "a" is final?
return this
Returns the object itself. In case of a.do() a is returned. What is this good for you might ask? It enables this:
a.do().do().do();
return this; - Being that, the return type is an A object, when the .do() method is called, the method will return this, this is the exact same instance that called it.
public A doSomething(final A a), the only contract here is that an A object is returned. What happens in the code block doesn't matter, as long as a null or class that extends A is returned.
final A a declaration, simply means the memory location address by variable a cannot be re-assigned.. i.e. a = null; or a = new A() would throw an exception
return this;
is exactly the same as any other return statement - it returns a reference to this. For example, if I had a variable Car a, the statement a.do() would return a reference to the same car a.
As for final, it doesn't mean immutability - it just means you can't reassign other data to the memory location. You can modify the Car that's already there - but not replace it with another Car.
a is final that means its memory address will not be changed again and a.do is simply calling the method do that will cause the move method of car to be called and return this returns the reference to the same object.
(First do is a keyword. So you renamed for clarity.)
return this; allows:
protected A doSomething(final A a ){
return a.do();
}
Which is exactly the same.
final variable declarations mean that you may assign only once to it (for fields), most often immediately at the declaration. So it is used for (dynamic) constants initialised only once.
do() is a method of class A. It can be called on any instance (object) of class A.
this refers to the current instance.
return this means that the method will return the instance of class A on which it (the method) is applied.
I'm not sure what such a method can be used for, though.
what does "return this;" mean here?
As mentioned over and over this it is always used within a context of an object and it is a reference to that object.
public A do() {
car.move(somewhere);
return this;
}
Return this, in the do() method just returns a reference to the current object.
Second is how a.do() works in method doSomething()? Method do() is supposed to return a value, yet it is not assigned anywhere?
Method do() just does some operation on the instance it is called from. because it is public it can be called from any place, and because it is not static it can be called only from an already created instance. That is why it needs to be called like a.do() and thats what it returns: the a reference.You dont have to assign it to anything, it will still operate within a reference and its operation will eventually update the a related state.
Lastly, I suppose that "a" returned from doSomething() was changed in this method. Is this allowed, as "a" is final?
Perfectly allowed. Java does not support pass by reference method so you can change the object the a reference points to however you cannot change the reference itself withing doSomething() method context.
Using return this; at the end of methods is a technique called Method Chaining and can be a very convenient way of performing a chain of operations on an object.
StringBuilder is a good example:
String s = new StringBuilder().append("Hello").insert(0, "Goodbye").delete(7, 12).append(" :)").toString();
NB: It can also be used to make code seem over-complex so it should only be used where appropriate.
This question already has answers here:
why java polymorphism not work in my example
(3 answers)
Closed 6 years ago.
Generally Overriding is the concept of Re-defining the meaning of the member in the sub class.Why variables are not behaving like methods while Overriding in java ?
For instance:
class Base {
int a = 10;
void display() {
System.out.println("Inside Base :");
}
}
class Derived extends Base {
int a = 99;
#Override
// method overriding
void display() {
System.out.println("Inside Derived :");
}
}
public class NewClass {
public static void main(String... a) {
Derived d = new Derived();
Base b = d;
b.display(); // Dynamic method dispatch
System.out.println("a=" + b.a);
}
}
Since data member a is package access specified, it is also available to the Derived class. But generally while calling the overridden method using the base class reference, the method that is redefined in derived class is called (Dynamic method dispatch)..but it is not the same for the variable..why.?
EXPECTED OUTPUT
Inside Derived :
a=99
OBTAINED OUTPUT:
Inside Derived :
a=10
Prints 10 - why the variable does not behave similar to method in the derived class?
Why the variables are not allowed to be overridden in the sub class?
You typed b as an instance of Base. So when the compiler needs to resolve b.a, it looks to the definition of Base for the meaning of b.a. There is no polymorphism for instance fields.
Because the only thing that polymorphism ever applies to in Java is instance method.
Hence, you can neither override static members, nor the instance member fields. By, having these members in a derived class with the same names you're simply hiding them with a new definition.
System.out.println("a="+b.a);
Although, Base b may point to a sub-class object (at runtime) the a above has already been bound to Base class at compile time (static binding). Hence, it prints 10.
Variables behave like that because they lack behavior. In other words, variables are passive.
There is nothing about a variable's definition that a derived class can reasonably change by overriding:
It cannot change its type, because doing so may break methods of the base class;
It cannot reduce its visibility, because that would break the substitution principle.
It cannot make it final without making it useless to the base class.
Therefore, member variables declared in derived classes hide variables from the base class.
There is no way to override a class variable. You do not override class variables in Java you hide them. Overriding is for instance methods.
In this case, it might be a good idea to write a getter method:
public int getA(){
return 99;
}
Now you can override it in a derived class.
First, we don't override any class variable. Methods only.
Second, if you would like to see that the variable value has been updated or replaced, you should rather declare it as "static int" instead of "int". In this way, it will work as everybody is sharing the same variable, and the new value will be put on it.
Third, if you would like to see that the variable value being assigned and used differently, you could design it as passing a parameter in constructor, or something similar, to make it work accordingly as you desire.
The answer to this has to do with variable scoping, not polymorphism. In other words, you're overriding that variable in the class scope. So, d.a will return the variable in Derived's class scope, but b.a will return the variable in Base's class scope.
In OOP (Object Oriented Programming) the idea is to hide the data in the object and let object only communicate with invoking methods. That's why variables cannot be overloaded, in fact they are "scoped"/"attached" to a specific class.
Also the derived class should not define a again, it is already defined in the base class, so simply set a on the object to the desired value, e.g:
class Base {
private int a = 10;
public int getA() { return a; }
public void setA(inta) { this.a = a; }
}
class Derived extends Base {
// adding new variables, override methods, ...
}
// then later:
Derived d = new Derived();
d.setA(99); // override the default value 10
What would happen if variables could override other variables? Suddenly your class has to be aware of what variables the parent class is using, lest you accidentally override one and break whatever was using it in the parent class. The whole point of encapsulation is to avoid having that kind of intimate knowledge of another object's internal state. So instead, variables shadow same-named other variables, and which one you see depends on what type you're trying to reach the variable through.
There's hope, though. If all you want is to override the value, you don't have to redeclare the variable. Just change the value in an init block. If the base class is harmed by you doing that, then it chose the wrong visibility for that variable.
class Base {
int a = 10;
}
class Derived extends Base {
{ a = 99; }
}
Of course, this doesn't work very well for final variables.
we don't override any class variable. Methods only.
If you would like to see that the variable value has been updated or
replaced, you should rather declare it as "static int" instead of
"int". In this way, it will work as everybody is sharing the same
variable, and the new value will be put on it.
If you would like to see that the variable value being assigned and
used differently, you could design it as passing a parameter in
constructor, or something similar, to make it work accordingly as
you desire.
Moreover, if variables are overridden then what is left with a parent class of its own,it breaches the class security if java would give the access to change the value of variable of parent class.
So I have a simple programming question that I can't seem to find the answer for. While browsing some code from Google I noticed that they put 'this' in front of a lot of methods in their code. What is the purpose of doing this? Does it have any benefits over not using it?
An example:
this.doMethod();
Compared to:
doMethod();
I'm sure its a simple answer, I just like being able to understand all of the code that I read.
No, it makes no difference at all for method calls. Use whichever you find more readable.
Note that it does make a difference when disambiguating between instance variables and parameters (or other local variables though). For example:
public void setFoo(int foo) {
this.foo = foo;
}
That's assigning the instance variable a value from the parameter - just using foo = foo; would be a no-op.
this represents the object instance of the current class. In programming practice, most of the time, it is used to break the ambiguity. e.g. in example, there is a class variable named name and method parameter named named, so this is used to differentiate the two.
public void setName(String name){
this.name= name;
}
If you don't have any ambiguity then it doesn't create much difference i.e. setName("John"); and this.setName("John"); is same thing. But still there is one difference. this.setName("John"); follows the same pattern as you are calling the method on objects(e.g. emp.setName("A");); here this representing the sane class object.
There is no difference between them at all. You always call a method on some reference. If you don't use any reference, this reference is implicit.
So, doMethod() is same as this.doMethod(). By using this, you just make it explicit.
One place where it is required to use this reference explicitly is the place where you are assigning the value of method/constructor parameter to the instance variable, and both have same name, as in the below example:
public Demo(int var) { // Constructor
this.var = var;
}
So, in the above example, this.var refers to instance variable and is different from var, which refers to constructor parameter.
As return type does not play any role in function overloading,and compiler only check the unique existence of only those part of code which is used at calling time..
Then why not this code contain error
class Temp{
Temp(){
System.out.println("Default Constructor");
}
void Temp(){
S.o.p("HEll");
}
public static void main(String a[]){
new Temp();
}
}
Output=Default constructor...//
I am shocked there is NO COMPILE TIME ERROR as copiler only check only those part of code which is used at calling time ,means compiler need to check only unique existence of Temp() and there is no unique existence of Temp().
Kindly elaborate
Because void Temp() is a method and you should invoke it on instance. It is allowed to declare method with name of the class but invocation is different. You can call only constructor with new operator.
You can read more about Constructor in JLS#8.8. Constructor Declarations
Constructors are never invoked by method invocation expressions (ยง15.12).
Major difference here you should note is constructor do not have return types and definition of overloading includes return types.
One is a constructor, the other is not.
Compiler distinguishes between method and constructor call using keyword new. Only constructor can be after new keyword.
Constructors don't require a return type and void Temp() will be treated as method not constructor.
When you call void Temp();, constructor with no arguments will be invoked.
Classes, methods, and fields reside in different namespaces. Compiler always can determine what construct is used, and easily differentiates new Temp() (class) from o.Temp() (method) and o.Temp (field).
Using Eclipse, you may avoid this usage:
See the line above "Apply" button
I have recently found out that no argument constructor and multiple argument constructor cannnot call each other in turns. What is the underlying reason of this limitation? Some might say that constructors are where resources are initialised. So they must not be called recursively. I want to know if this is the only reason or not. Functions/methods/procedures can be called recursively. Why not constructors?
The answer lies in the fact that the call to another constructor is the first line of any constructor and hence your if condition to break out of recursion will never be executed and hence stack overflow.
The main purpose of the constructor is to initialize all the global variables described in a particular class.
For Example:
public class Addition(){
int value1;
int value2;
public Addition(){ // default constructor
a=10;
b=10;
}
public Addition(int a, int b){
this(); // constructors having parameters , overloaded constructor
value1=a;
value2=b;
}
}
public class Main(){
public static void main(){
Addition addition = new Addition(); //or
Addition addition = new Addition(15,15);
}
}
Here, if you want to make instance of the class you can either make instance by calling default constructor or by calling constructor having parameters. So the constructors are overloaded and not overridden. If you want to call another constructor, that can only be done be putting either this() or super() in the first line of the constructor. But this is not prefferable.
Constructors are not intended to be called explicitly outside object initialization, because it's restricted in most (I guess all) languages. Instead, you can create an additional protected Init(...) member function and call it inside the constructor.
Your statement that constructor cannot call other constructors are not true for every programming languages. At least I know Java can do this, while C++ cannot. But you could easily overcome this limitation by writing a private __init function and let all your constructors call it.
In all languages you've listed objects contain finite (and normally short) set of properties. Each property could contain recursive structure (i.e. list), but it still represented by a single property in the object.
I don't see need to recursively call constructors. It feels like a strange use recursion to initialize several well know properties.
As you've said you can call constructors in non-recursive way to share code in some languages you've mentioned.
C#: Using Constructors
public Employee(int weeklySalary, int numberOfWeeks)
: this(weeklySalary * numberOfWeeks)
{
}