super() with no arguments in java - java

I'm checking out this tutorial:
http://www.developerfeed.com/building-todo-list-app-android-using-sqlite
What I do not understand is this piece of code:
public Task()
{
this.taskName=null;
this.status=0;
}
public Task(String taskName, int status) {
super();
this.taskName = taskName;
this.status = status;
}
Why the need to call super() on this point?
Edit: The reason why I'm asking is because I personaly see no need to put it there.

Why the need to call super() on this point?
There is no such need. The compiler will put it in by default.

There is not a need to call super() with no arguments. When you call a constructor of a sub class the 0 parameter superclass constructor gets called automatically. It does not matter if you call it or not.

super() specifically calls the constructor of the class that the current class is inheriting.
In this case, the call for the super() method is calling the constructor for the Object class, which all classes primitively inherit.
And you are right; in this particular case, the call for super() is not required or needed at all.
An example of using super() can be easily made with the reference of the JFrame class.
public class MyFrame extends JFrame {
public static final String TITLE = "My JFrame";
public MyFrame() {
//call constructor of super class (JFrame)
//the String parameter is the title of the frame
super(TITLE);
//other code here
}
//assume other methods are here
}

super(), is for calling the father constructor , i think that your class is not extending from some class, so in JAVA the pure class, extend from Object. When you call super(), you are calling the father constructor in this case Object().
I your constructor public Task(String taskName, int status) You are not calling to public Task() your class is calling the Object constructor Object().
Check this.
http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html

Super is used to call the parent class. When you extend a class you can call a function or variable from the parent class in the child class.
For example Look at this pseudo code which child uses an int defined in the father class
Public class Child extends Father{
Int age = 21;
Int ageDiff = Super.age - age;
}
Super in your code is not needed.

Related

Why is calculate() in the constructor executed?

in summary
WeatherCalculator calculator = WeatherCalculatorFactory.getInstance(Mode.valueOf(mode));
if(mode==Mode.DEW_POINT)
{
return new DewPointCalculator();
}
public class DewPointCalculator extends WeatherCalculator{
//default constructor
public DewPointCalculator()
{
this(null);
}
public WeatherCalculator(WeatherData weatherData) {
this.weatherData = weatherData;
calculate(); //calculate overriding
}
public WeatherCalculator()
{
this(null);
}
The line breaks are all different classes.
I wonder why calculate() in the constructor is executed when no object has been passed here.
You do call the first constructor with this(null). To call the second, no-argument constructor you can use this().
However, the second constructor still calls this(null) so the first constructor will be called either way.
The thing about null is that null can be anything, and anything can be null.
So by calling this(null) you are passing a WeatherData, it is just null (and using it would result in an error).
You are overloading constructors in class WeatherCalculator this is known as Explicit Constructor Invocation
You have two constructors in the class WeatherCalculator
WeatherCalculator() //Non parameterized constructor
WeatherCalculator(WeatherData weatherData) //parameterized constructor
what happens when you create an object of the WeatherCalculator class the WeatherCalculator() constructor is called which calls this(null) the parameterized constructor(WeatherCalculator(WeatherData weatherData)) and the calculate method is executed.

Sometime it creates an error because there is no constructor and sometimes it's OK [duplicate]

so I have a java class called User that contains a constructor like this:
public class User extends Visitor {
public User(String UName, String Ufname){
setName(UName);
setFname(Ufname);
}
}
And then the he problems occur in my other class called Admin:
public class Admin extends User { //error "Implicit super constructor User() is undefined for default constructor. Must define an explicit constructor"
//public Admin() { } //tried to add empty constructor but error stays there
//}
public void manage_items() {
throw new UnsupportedOperationException();
}
public void manage_users() {
throw new UnsupportedOperationException();
}
}
I am getting the error Implicit super constructor User() is undefined for default constructor. Must define an explicit constructor at the place marked in the code. I don't know how to fix that, and I'm really new to java.
If you don't add a constructor to a class, one is automatically added for you. For the Admin class, it will look like this:
public Admin() {
super();
}
The call super() is calling the following constructor in the parent User class:
public User() {
super();
}
As this constructor does not exist, you are receiving the error message.
See here for more info on default constructors:
http://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
You don't have to provide any constructors for your class, but you must be careful when doing this. The compiler automatically provides a no-argument, default constructor for any class without constructors. This default constructor will call the no-argument constructor of the superclass. In this situation, the compiler will complain if the superclass doesn't have a no-argument constructor so you must verify that it does. If your class has no explicit superclass, then it has an implicit superclass of Object, which does have a no-argument constructor.*
You must call the Visitor's constructor on the first like of the constructor that extends the Visitor's class, using super():
public User(String UName,String Ufname){
super();
setName(UName);
setFname(Ufname);
}
and if you want Admin to have a custom constructor too, you must call:
super(uname, ufname) // String, String - pass the params of the superclass cunstructor
So:
public Admin() {
super(someString, someString);
}
Your Admin class extends User, and User doesn't have a default construtor. You need to use the constructor that takes two String(s) with super. Something like,
public Admin() {
super("a", "b"); // <-- first line.
}
Alternatively, you could add a no-args constructor to User
public User() {
}
And then your current Admin would compile.
You need to know two things:
At start of each constructor there is call to constructor of superclass. It is represented by
super() - invoke no-argument constructor of superclass
super(your,arguments) - invoke constructor handling arguments with same types as passed to super(..).
If we want to use no-argument constructor we don't actually need to write super() because compiler will add code representing call to super() in binaries, but compiler can't do this nice thing for us if we want to call super with arguments because
it can't decide which constructor with arguments of superclass you want to use,
and what values (arguments) should be passed there,
so in that case you need to explicitly write super(your,arguments) at start of your constructor yourself.
If you will not add any constructor to your class compiler will add default constructor, which will have no arguments and its only instruction will be calling no-argument constructor of superclass super(). In other words code of classes like
class Base{}
class Derived extends Base{}
is same as this code
class Base extends Object{
Base(){
super();//will try to call Object() constructor
}
}
class Derived extends Base{
Derived(){
super();//will try to call Base() constructor
}
}
Now since in User class there is only one constructor User(String UName,String Ufname) when you try to compile
public class Admin extends User {
public void manage_items() {
//...
}
public void manage_users() {
//...
}
}
compiler see it as
public class Admin extends User {
public Admin(){
super();
}
public void manage_items() {
//...
}
public void manage_users() {
//...
}
}
Now as you see problem lies in
public Admin(){
super();
}
because super() will try to invoke no-argument User() constructor, but there is no such constructor because only existing constructor in User class is User(String,String).
So to make this work you need to add Admin constructor and at its start call super(someString, someString).
So consider adding to your Admin class constructor like this one:
public Admin(String aName,String Afname){
super(aName, Afname);
//here you can place rest of your constructors code
}

Is there a way I can call a parent class constructor that takes parameters from a child class that does not have a constructor of it's own?

As we all know, the parent class must be constructed before the child class; and if the parent's class constructor takes parameters, then the constructor of the parent class must be called explicitly. My question is, how do you call a parent class constructor that takes parameters explicitly from a child class, if the child class does not have a constructor itself?
public class A {
public String text;
public A(String text) {
this.text = text;
}
}
public class B extends A {
// Now I must call the constructor of A explicitly (other wise I'll get a
// compilation error) but how can I do that without a constructor here?
}
The answer is: you can't!
In case the super class has a parameter free constructor, the compiler can add one like that for you in subclass, too.
But when the super class needs parameters, the compiler has no idea where these should come from.
So: consider adding a no args constructor to the super class, it could invoke the other constructor and pass some sort of default values. Alternatively, you can do the same in the derived class.
And just for the record: there are no Java classes without constructors. It is just that the compiler might create one for you behind the covers. From that point of view, your question does not make much sense.
You are getting compilation error because there is no default constructor in class A. You can create a no-arg constructor in B and pass some default text to A's contructor, or create a no-arg constructor in A.
public B() {
super("some default text"); //will call public A(String text)
}
If you're not willing to call the parent constructor directly, you'll just need to add a constructor with the same parameters in the child class that just calls the parent constructor.
public class A {
public String text;
public A(String text)
{
this.text = text;
}
}
public class B extends A
{
public B(String text)
{
super(text);
}
}

Don't create supperclass instance in contructor of subclass, but fully legal

I read in scjp guide as following
In fact, you can't make a new object without invoking not just the
constructor of the object's actual class type, but also the
constructor of each of its superclasses!
For example
public class Person{
}
public class Employee extends Person{
public Employee(){
}
}
I don't create a Person instance but it is legal.
Please explain for me, thank for your help.
Whenever you instantiate a subclass, it'll call your superclass' constructor first.
You can find more about this here: JSL ยง8.8.7
Person.java
public class Person {
public Person() {
System.out.println("Super class constructor called");
}
}
Employee.java
public class Employee extends Person {
public Employee() {
System.out.println("Sub class constructor called");
}
}
If you then instantiate your Employee:
Employee e = new Employee();
Output:
Super class constructor called
Sub class constructor called
What they actually mean is
When you are creating a subclass object, i.e. its constructor is getting called, then superclass constructor gets callued internall
This is because for the default no-argument constructor there is a default super() call to the superclass constructor.
This goes on like the class hierarchy until the Object class.
In fact, if you do not write a no-argument constructor in superclass then the subclass declaration will throw compiler error.
public class Super {
public Super(int num){
}
}
public class Sub extends Super {
}
Here, class Sub will not compile giving the error Implicit super constructor Super() is undefined for default constructor because it cannot find a no-argument constructor in super class as the default no-argument constructor i.e. provided by compiler will have an implicit call to super().
Compiler provides a default no arg constructor only if there is no other constructor defined
As we have explicitly defined Super(int num), we will have to exlicitly create no-arg constructor as follows.
public Super(){
}
First, you don't have to create a parent instance (Parent) to instantiate a child class (Employee). You must have understood wrong.
Invoking the constructor of the parent class doesn't mean to create a new parent instance object (you're not calling it with new, so no new instance is created). You are creating a child instance, and for this, you need to first invoke the parent's constructor because of inheritance. Imagine for example the parent class has private fields that must be initialized in the constructor (for example private final fields). This fields cannot be accessed from the child class, but they can be initialized from the parent class constructor. You need to initialize this fields in the child instance, and the only way is calling super().
In this case Person has a default contructor which is invoked by default, no need to explicitly call it.
But in case Person has no default constructor, you need to call it explicitly. For example:
public class Person{
private final String name;
public Person(final String name) {
this.name = name;
}
}
public class Employee extends Person {
public Employee() {
}
}
This will not compile. You need to modify Employee so it calls Person constructor explicitly. For example:
public class Employee extends Person {
public Employee(final String name) {
super(name);
}
}
Superclass' nullary constructor is implicitly called.
Its because of constructor chaining:
First statement inside a any constructor by default is super();(This is a call to super class default constructor).
I don't create a Person instance but it is legal:
thats because you have a default constructor in Person class. So Employee class constructor can actually invoke super class constructor. Person()
Bottom line, the current class in which you are declaring a constructor, all the constructor upto the base class should be accessible via super(). If not, you have to explicitly make them accessible by explicitly making a call via super with proper parameters.
You have encountered one of the oddities of java.
If you don't define any constructors, the default, or "no args", constructor is implicitly defined. It's like invisible code.
If you define any constructor, args or no args, the implicit default constructor goes away.
To further compound the mystery, the first line of any subclass constructor must be to call a constructor of the super class. If you don't explicitly call one, the no-args constructor is implicitly called.

Java Constructor weird behaviour

I've run this code
public class Redimix extends Concrete{
Redimix(){
System.out.println("r ");
}
public static void main(String[] args) {
new Redimix();
}
}
class Concrete extends Sand{
Concrete() { System.out.print("c "); }
private Concrete(String s) { }
}
abstract class Sand{
Sand(){
System.out.print("s ");
}
}
and it printed out s c r but what I was expecting is that only r my question what is the logical explanation for this?
if a parent base class is an abstract class that has a constructor and then we create another class then extend it to the base class (In our Case Concrete extends Sand) and we then create another class then extend it to the concrete class name (In our case redimix) will all constructors from the hierarchy will be called?(from top to bottom)
A constructor of the superclass is always called as the first action of a constructor.
If you do not explicitly invoke a constructor of the superclass, the default constructor (the "no args" one) is implicitly invoked.
That is correct. The parent object's constructor is always called before the childs. This ensures that the object is in a valid state and that the object that has extended another class can always know what state the object is in.
Here is the code that you provided, after the compiler has inserted the implicit constructor calls in on your behave. Note that super(); is always called first.
public class Redimix extends Concrete{
Redimix(){
super();
System.out.println("r ");
}
public static void main(String[] args) {
new Redimix();
}
}
class Concrete extends Sand{
Concrete() { super(); System.out.print("c "); }
private Concrete(String s) { }
}
abstract class Sand{
Sand(){
super(); // invoking the constructor for java.lang.Object
System.out.print("s ");
}
}
In each constructor, parent constructor is also called.
In every constructor, first statement is always super() which is calling super class constructor except for Object class
You need to understand constructor chaining for this. When you make a call to any constructor all the super class constructors are invoked first. In you constructor definition, if you dont have one compiler will add a no argument call to super class constructor something like this : super();
This is because, all the class in the hierarchy must be build before you actual class, because your class is dependent on its super class.
This class to the super class constructor should always be the first statement in your constructor definition because they must be build before this concerned class. So Object class constructor is always the first to be executed.

Categories

Resources