This question already has answers here:
Require a default constructor in java?
(3 answers)
Closed 8 years ago.
I've tried running the following code which gives me a constructor A in class A cannot be applied to given types error.
class A{
int a;
A(int b){
a = b;
}
}
public static void main (String[] args) throws java.lang.Exception
{
A a = new A();
System.out.println(a.a);
}
If I remove the c'tor from class A however the code runs as expected (and outputs 0). It seems that if another c'tor exists there is no default c'tor (and an argument less c'tor exists only if it is written). Am I correct?
More importantly, why is this?
If you don't create a constructor then there is a constructor by default as below
public YourClass(){
}
But if you create a constructor like below:
public YourClass(int x){
}
Then you won't have a constructor by default i.e.
public YourClass(){
//this won't exist
}
So you have to do
YourClass anObject = new YourClass(5);//you can do this.
And hence you cannot do something like
YourClass anObject = new YourClass();//you cannot do this
In order to do this you need to create a constructor by yourself as
public YourClass(){
//this time you must create this
}
For the question why?, I doubt there is any reason. This is the way OOP has moved.
Once you defined a non-empty constructor, the non-empty conscrutor isn't implicite and you have to explicite it.
public A() {
}
Related
This question already has answers here:
How do I call one constructor from another in Java?
(22 answers)
Closed 3 years ago.
I am extending the API of a class that I am working on and would like to make it backward compatible - so that it doesn't break any existing users of the class. I have created the new functionality by adding a new parameter to the constructor.
So that I don't repeat code (I could copy-paste code from the old constructor into the new) I would like to change the existing constructor to call the new constructor passing 0 as the default for the new parameter but I am getting a compilation error, method call expected.
Is what I am trying to do not possible (method overloading is not supported?) or am missing something?
To help show what I mean, please see the simple example below,
public abstract class AbstractCalculator {
int result;
// new parameter being added
public AbstractCalculator(int a, int b){
result = a + b;
}
// existing functionality
public AbstractCalculator(int a){
//compilation error here - Method call expected
AbstractCalculator(a, 0);
}
}
public class Calculator extends AbstractCalculator{
public Calculator(int a){
super(a);
}
public static void main(String args []){
Calculator calc = new Calculator(4);
System.out.println(calc.getResult());
}
}
// existing functionality
public AbstractCalculator(int a){
this(a, 0);
}
This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
When should I use "this" in a class?
(17 answers)
Closed 4 years ago.
I have a question.
Please don't mark it as duplicate, Go through the question once. I can't find an answer to this specific situation/condition, If you feel it has a specific answer then only mark duplicate. Marking it duplicate makes my question remain a question without an answer.
What's the difference between calling a method with/without this as a keyword. Which one is better?
The question specifically applies for a single class.
Please have a look at the sample code below to fully understand the question.
public class ThisSample {
public static void main(String[] args) {
ThisSample sample = new ThisSample();
sample.methodOne();
}
public void methodOne() {
System.out.println("Method 1 called");
this.methodTwo(); //Line 1
methodTwo(); // Line 2
}
public void methodTwo() {
System.out.println("Method 2 called");
}
}
What difference (Advantage/disadvantage/implication) does the 2 lines (Line 1 & Line 2) in the code make?
Thanks & Regards,
Yadvendra
'This' task is to differentiate object property from method parameter. In presented code usage of this does nothing. However the most common use is like in this example:
public class Service {
private ServiceA serviceA;
private ServiceB serviceB;
// Here 'this' is used to make sure that class instance
// properties are filled with constructor parameters
public Service(ServiceA serviceA, ServiceB serviceB) {
this.serviceA = serviceA;
this.serviceB = serviceB;
}
}
this is used to specify that you're talking about the method methodTwo from the current instance of the class ThisSample.
If you'd have another class called AnotherSample:
public class AnotherSample{
public static void methodThree()
{
// some code
}
}
You could use the method methodThree by calling it as follows AnotherSample.methodThree();.
In summary: this just specifies that you're using the instance of the class you're currently coding in.
In the example, you have given, the difference is nothing. Let me modify your code a bit:
public class ThisSample {
int variable;
public static void main(String[] args) {
ThisSample sample = new ThisSample();
sample.methodOne(3);
sample.methodTwo(5);
}
public void methodOne(int variable) {
this.variable = variable;
System.out.println("variable is: " + this.variable);
}
public void methodTwo(int variable) {
variable = variable;
System.out.println("variable is: " + this.variable);
}
}
Here, for method 2, you must use this.variable to set the value in the instance variable. Otherwise, both method will print 3 here. The second method is also printing three because you set 3 in method one.
Now in method 2, in
variable = variable
line, both variable are paramater of mathod 2. But when you are writing,
this.variable = variable;
you are telling, left one is instance variable of this object and right part is assigned to instance variable of this object.
Edit:
If you want to know "which is more preferred", then see this link too. Here using this is said "redundant". Link is: https://softwareengineering.stackexchange.com/a/113434/162116
Here, it is also said that, I should refactor the code if I actually need this to deduce the instance variable.
Please tell me if I have the proper understanding of the following code:
public class Test {
public static void main(String[] args) {
A a = new A();
a.print();
}
}
class A {
String s;
A(String s) {
this.s = s;
}
void print() {
System.out.println(s);
}
}
The line “A a = new A();” invokes the class/constructor to create a new object with reference variable “a”. Class A has a defined constructor that requires a string argument, thus it does not have the default constructor. This means that the instantiation without any string arguments causes a compiler error.
If I were to add a string argument into the instantiation, e.g. A a = new A("goldfish"); the program would compile and run.
I am not sure if I have used the right vocabulary for this, so feel free to correct anything that is inaccurate/confusing. Thanks!
Your understanding is pretty much correct. The one thing that I would change is "create a new object" to "create a new instance of A" with a reference to a java.lang.String in parameter s. In this case the constructor assigns that parameter to a field, but it can do something else with it entirely (such as use it to calculate a different value for some field).
What you wrote is roughly correct.
To be more precise: "invokes the class/constructor" is not entirely correct. A a = new A(); intends to invoke the constructor (invoking a class doesn't mean anything).
Though constructors are not methods, you can think of them a bit like methods: if your class has defined a method like so :
public void myMethod(String s) { ... }
Then trying to call myMethod() without any argument would fail. It's the same here.
This question already has answers here:
Calling superclass from a subclass constructor in Java
(4 answers)
Closed 7 years ago.
What I need to do: //Constructor that initializes b to inVal1 and the inherited a
// to inVal2 by using the BaseExample constructor.
public DerivedExample(int inVal1, int inVal2);
How do you call the class BaseExample's variable, in class DerivedExample by using BaseExample constructor in DerivedExample constructor? I have checked numerous articles in stackoverflow and it hasn't helped figure this out. Any help will be greatly appreciated. This is my code:
BaseExample Class (and no I am not allowed to make the variable protected on this example):
public class BaseExample {
private int a;
public BaseExample(int inVal) {
a = inVal;
}
public BaseExample(BaseExample other){
a = other.a;
}
public String toString(){
return String.valueOf(a);
}
}
DerivedExample Class (Updated):
public class DerivedExample extends BaseExample {
private int b;
public DerivedExample(int inVal1, int inVal2){
super(inVal2);
a = inVal2;
}
}
The super method worked. Now how would I call it if I am asked this:
Returns a reference to a string containing the value stored in
the inherited varible a followed by a colon followed by the
value stored in b
public String toString()
I have tried this:
public String toString(){
int base = new BaseExample(b);
return String.valueOf(base:this.b);
}
If I put two returns, it would give me an error of unreachable code. And if I put a super inside the valueOf it doesn't work. And this doesn't work as well. How is this executed?
If I understand correctly, this might be of use to you. Super can be used to call the base class's constructor to instantiate its variables for you.
This question already has answers here:
Uninitialized variables and members in Java
(7 answers)
Closed 8 years ago.
I have a question that why this code is giving me an error while i am trying to call a static function defined within a class through a class reference and it makes possible to call a static function when i am creating an object of a reference.
public class Example
{
public static void main(String args[])
{
Example t;
t.method();//getting error
Example t1=new Example t1();
t1.method();//it runs successfully
}
public static void method()
{
System.out.println("NullPointerException");
}
}
You should not call a static method on an instance of the class. You should use name of the class itself:
Example.method()
Also when you declare a variable and left it without initialization, It will not be initialized (Local variables) and when you try to call a method on it, you will get error
t is not initialised when you call t.method();. You therefore get a NullPointer on the non-instanciated t object.
public class Example
{
public static void main(String args[])
{
Example t; // t points to nothing (not even null, actually, its as if it doesn't exist at all)
t.method();//getting error // how can you call a method of example with a reference to nothing.
Example t1=new Example t1(); // t1 points to an Example object.
t1.method();//it runs successfully // works fine , but is not suggested as the method is at class level, not at instance level. use Example.method()
}
public static void method()
{
System.out.println("NullPointerException");
}
}
that is possible, but if you want to call anything through a reference, you need to instantiate it first.
do remember also: Java has methods, not functions. So, change:
Example t;
in
Example t = new Example();
and try again