Question about constructor of superclass and subclass - java

Why the the code (1) is not result an error while code (2) (3) will?
I think when the subclass calls the constructor, it will calls super class constructor first, but I do not know why the code (1) is right while other two are wrong.
//(1)
public class Parent {
public int a;
public Parent() {
this.a = 0;
}
}
public class Child extends Parent {
public Child() {}
}
//(2)
public class Parent {
public int a;
public Parent(int number) {
this.a = number;
}
}
public class Child extends Parent {
public Child() {}
}
//(3)
public class Parent {
public int a;
public Parent(int number) {
this.a = number;
}
}
public class Child extends Parent {
public Child(int numb) {
}
}
Code(1) is right while other two are wrong.

Note: If a constructor does not explicitly invoke a superclass
constructor, the Java compiler automatically inserts a call to the
no-argument constructor of the superclass. If the super class does not
have a no-argument constructor, you will get a compile-time error.
Object does have such a constructor, so if Object is the only
superclass, there is no problem.
So, here it is, your code (2)(3) doesn’t have a no-argument constructor, and also you didn’t explicitly invoke a has-argument constructor, you got a compile-time error. More details from https://docs.oracle.com/javase/tutorial/java/IandI/super.html

In code 1, the constructor for Parent has no arguments, so a call to the default one is implicit:
public Child () {
super();
} /* This code is not necessary, but is implied. */
But in codes 2 and 3, the constructor has a parameter, and since there is no overload provided with no parameters, then a call to the superclass constructor must be provided. To do this, you must reference super().
public class Parent {
public int a;
public Parent(int number) {
this.a = number;
}
}
public class Child extends Parent {
public Child(int numb) {
super(numb); // Calls Parent(int) and sets this instance’s Parent.a value to numb.
}
}

Related

super.a = b instead of super(b)

I'm learning the super keyword and accidentally get this, here's an example :
public class A {
double a;
public A (double a) {
this.a = a;
}
}
public class B extends A {
public B (double b) {
super.a = b; //***
}
}
The usual way to do this as in the tutorials is super(b) to reusing its parent constructor, but what is wrong with super.a = b?
There is no "constructor inheritance" in Java. If the super class doesn't have a no-arg constructor, you must explicitly call its constructor (or one of them if there are several). If you don't, you'll get a compilation error.
When you write your class A like this:
public class A {
double a;
public A(double a) {
this.a = a;
}
}
you overwrite the default constructor and in the line this.a = a you are accessing instance variable and setting the values and in class B:
public class B extends A {
public B(double b) {
super.a = b; // ***
}
}
you are trying to access instance variables of Class B through the constructor because super.a in here , the super referes to the constructor and its wrong and throwing the Implicit super constructor A() is undefined. Must explicitly invoke another constructor which means: in Class B its looking for a constructor which has no parameter because you overwrite the default constructor of class and it can't recognize it by calling super.a = b so you have to call the super constructor as a function and in the first line of code:
public class B extends A {
public B(double b) {
super(b);
super.a = b; // ***
}
}

Extending an abstract constructor?

So I've come across a bit of a snag in some code that I'm working with. Essentially I have the following three tidbits of code:
Abstract class:
public abstract class TestParent {
int size;
public TestParent(int i){
size = i;
}
}
Child Class:
public class TestChild extends TestParent{
public void mult(){
System.out.println(this.size * 5);
}
}
Implementation:
public class TestTest {
public static void main(String args[]) {
TestChild Test = new TestChild(2);
Test.mult();
}
}
Consider the following case of abstract class and extends implementation.
https://stackoverflow.com/a/260755/1071979
abstract class Product {
int multiplyBy;
public Product( int multiplyBy ) {
this.multiplyBy = multiplyBy;
}
public int mutiply(int val) {
return muliplyBy * val;
}
}
class TimesTwo extends Product {
public TimesTwo() {
super(2);
}
}
class TimesWhat extends Product {
public TimesWhat(int what) {
super(what);
}
}
The superclass Product is abstract and has a constructor. The concrete class TimesTwo has a default constructor that just hardcodes the value 2. The concrete class TimesWhat has a constructor that allows the caller to specify the value.
NOTE: As there is no default (or no-arg) constructor in the parent abstract class the constructor used in subclasses must be specified.
Abstract constructors will frequently be used to enforce class constraints or invariants such as the minimum fields required to setup the class.
public class TestChild extends TestParent{
public TestChild(int i){
super(i); // Call to the parent's constructor.
}
public void mult(){
System.out.println(super.size * 5);
}
}
Use super to call parent (TestParent.TestParent(int)) constructor:
public class TestChild extends TestParent{
public TestChild(int i) {
super(i);
}
//...
}
or if you want to use some constant:
public TestChild() {
super(42);
}
Note that there is no such thing as abstract constructor in Java. Essentially there is only one constructor in TestParent which must be called before calling TestChild constructor.
Also note that super() must always be the first statement.
When you have explicit constructor defined in super class and no constructor without arguments defined, your child class should explicitly call the super class constructor.
public class TestChild extends TestParent{
TestChild ()
{
super(5);
}
}
or, if you don't want call super class constructor with parameters, you need to add constructor with no arguments in super class.
public abstract class TestParent {
int size;
public TestParent(){
}
public TestParent(int i){
size = i;
}
}
You code wont compile because your base class does not have a default constructor. Either you need to provide it in base class or you need to provide parameterized constructor in derived class and invoke super.
public class TestChild extends TestParent{
public TestChild (int i)
{
super(i * 2);
}
}
This code would use the double of i. This is an overriding, though i'm not sure what you want to ask.
Other solution:
public class TestChild extends TestParent{
public TestChild (int i)
{
super(i);
this.size = 105;
}
}
For this solution, size must be protected or public.

In Java , Can't access protected members of super-class from sub-class

class Super {
protected int a;
protected Super(int a) { this.a = a; }
}
class Sub extends Super {
public Sub(int a) { super(a); }
public Sub() { this.a = 5; }
}
public Sub() { this.a = 5; }
this.a=5 doesn't work. Why is this so? Protected and public members should be inherited.
The problem isn't that you access the variable, but that you don't call the base constructor:
class Super {
protected int a;
protected Super(int a) { this.a = a; }
}
class Sub extends Super {
public Sub(int a) { super(a); }
public Sub() {
super(0); // <-- call base constructor
this.a = 5;
}
}
This happens because you didn't define a default constructor for Super, so derived classes don't know which constructor to call if you're not specifying one.
Your parameterless constructor in Sub is attempting to implicitly invoke a parameterless constructor in Super which doesn't exist, which is (I assume) why you're getting a compile error.
What does not work? Works for me...
What you do not have is a default constructor - in public Sub() {this.a = 5; } the parent default constructor is called, which you have not provided. If I compiler your code I get:
cannot find symbol constructor Super()
So you either have to have a default constructor or do: public Sub() { super(5); }

Passing construction to super class

I was wondering if i have an abstract super class with x different constructors, and i want to be able to use all those constructors in a subclass, do i have to write all x constructors in the subclass and just let them all call super(...) ? Seems like redundant code..
An example for the clarity:
public class SuperClass {
public SuperClass() {
...
}
public SuperClass(double d) {
...
}
public SuperClass(BigDecimal b) {
...
}
public SuperClass(BigDecimal b, String s) {
...
}
[...]
}
Do i than need:
public class SuperClass {
public SubClass() {
super();
}
public SubClass(double d) {
super(d);
}
public SubClass(BigDecimal b) {
super(b);
}
public SuperClass(BigDecimal b, String s) {
super(b, s);
}
[...]
}
But you have to do it this way. As this way you are deciding what you want to expose in the subclass. Also some constructors might be not appropriate for a sub class thus this is not working by default without you coding it explicitly.
You do not need to supply constructors for every overload of base's constructors. You simply need one. If your base constructor offers a default (parameterless) constructor, then you do not even need to provide a constructor yourself. The compiler will automatically generate a default constructor for your class that automatically calls the default constructor of your base class.
Note: it is not necessary to call super() directly, as it is implied without parameters. It is only required when no default constructor exists.
Seeing that many different constructors, and the fact that you do not need them all might imply that the parent class is doing too much.
you can have a code like this:
public class SuperClass {
public SuperClass() {
...
}
public SuperClass(double d) {
...
}
public SuperClass(BigDecimal b) {
}
public SuperClass(BigDecimal b, String s) {
this(b);
}
[...]
}
And have a subclass as:
public class SubClass extends SuperClass{
public SubClass() {
super();
}
public SubClass(double d) {
super(d);
}
public SuperClass(BigDecimal b, String s) {
super(b, s);
}
[...]
}
If you want every type of constructor in both parenr and child, then yes, you need to specify them explicitly, but no need to call super() explicitly.

super() in Java

Is super() used to call the parent constructor?
Please explain super().
super() calls the parent constructor with no arguments.
It can be used also with arguments. I.e. super(argument1) and it will call the constructor that accepts 1 parameter of the type of argument1 (if exists).
Also it can be used to call methods from the parent. I.e. super.aMethod()
More info and tutorial here
Some facts:
super() is used to call the immediate parent.
super() can be used with instance members, i.e., instance variables and instance methods.
super() can be used within a constructor to call the constructor of the parent class.
OK, now let’s practically implement these points of super().
Check out the difference between program 1 and 2. Here, program 2 proofs our first statement of super() in Java.
Program 1
class Base
{
int a = 100;
}
class Sup1 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup1().Show();
}
}
Output:
200
200
Now check out program 2 and try to figure out the main difference.
Program 2
class Base
{
int a = 100;
}
class Sup2 extends Base
{
int a = 200;
void Show()
{
System.out.println(super.a);
System.out.println(a);
}
public static void main(String[] args)
{
new Sup2().Show();
}
}
Output:
100
200
In program 1, the output was only of the derived class. It couldn't print the variable of neither the base class nor the parent class. But in program 2, we used super() with variable a while printing its output, and instead of printing the value of variable a of the derived class, it printed the value of variable a of the base class. So it proves that super() is used to call the immediate parent.
OK, now check out the difference between program 3 and program 4.
Program 3
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup3 extends Base
{
int a = 200;
void Show()
{
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup3().Show();
}
}
Output:
200
Here the output is 200. When we called Show(), the Show() function of the derived class was called. But what should we do if we want to call the Show() function of the parent class? Check out program 4 for the solution.
Program 4
class Base
{
int a = 100;
void Show()
{
System.out.println(a);
}
}
class Sup4 extends Base
{
int a = 200;
void Show()
{
super.Show();
System.out.println(a);
}
public static void Main(String[] args)
{
new Sup4().Show();
}
}
Output:
100
200
Here we are getting two outputs, 100 and 200. When the Show() function of the derived class is invoked, it first calls the Show() function of the parent class, because inside the Show() function of the derived class, we called the Show() function of the parent class by putting the super keyword before the function name.
Source article: Java: Calling super()
Yes. super(...) will invoke the constructor of the super-class.
Illustration:
Stand alone example:
class Animal {
public Animal(String arg) {
System.out.println("Constructing an animal: " + arg);
}
}
class Dog extends Animal {
public Dog() {
super("From Dog constructor");
System.out.println("Constructing a dog.");
}
}
public class Test {
public static void main(String[] a) {
new Dog();
}
}
Prints:
Constructing an animal: From Dog constructor
Constructing a dog.
Is super() is used to call the parent constructor?
Yes.
Pls explain about Super().
super() is a special use of the super keyword where you call a parameterless parent constructor. In general, the super keyword can be used to call overridden methods, access hidden fields or invoke a superclass's constructor.
Here's the official tutorial
Calling the no-arguments super constructor is just a waste of screen space and programmer time. The compiler generates exactly the same code, whether you write it or not.
class Explicit() {
Explicit() {
super();
}
}
class Implicit {
Implicit() {
}
}
Yes, super() (lowercase) calls a constructor of the parent class. You can include arguments: super(foo, bar)
There is also a super keyword, that you can use in methods to invoke a method of the superclass
A quick google for "Java super" results in this
That is correct. Super is used to call the parent constructor. So suppose you have a code block like so
class A{
int n;
public A(int x){
n = x;
}
}
class B extends A{
int m;
public B(int x, int y){
super(x);
m = y;
}
}
Then you can assign a value to the member variable n.
I have seen all the answers. But everyone forgot to mention one very important point:
super() should be called or used in the first line of the constructor.
Just super(); alone will call the default constructor, if it exists of a class's superclass. But you must explicitly write the default constructor yourself. If you don't a Java will generate one for you with no implementations, save super(); , referring to the universal Superclass Object, and you can't call it in a subclass.
public class Alien{
public Alien(){ //Default constructor is written out by user
/** Implementation not shown…**/
}
}
public class WeirdAlien extends Alien{
public WeirdAlien(){
super(); //calls the default constructor in Alien.
}
}
For example, in selenium automation, you have a PageObject which can use its parent's constructor like this:
public class DeveloperSteps extends ScenarioSteps {
public DeveloperSteps(Pages pages) {
super(pages);
}........
I would like to share with codes whatever I understood.
The super keyword in java is a reference variable that is used to refer parent class objects. It is majorly used in the following contexts:-
1. Use of super with variables:
class Vehicle
{
int maxSpeed = 120;
}
/* sub class Car extending vehicle */
class Car extends Vehicle
{
int maxSpeed = 180;
void display()
{
/* print maxSpeed of base class (vehicle) */
System.out.println("Maximum Speed: " + super.maxSpeed);
}
}
/* Driver program to test */
class Test
{
public static void main(String[] args)
{
Car small = new Car();
small.display();
}
}
Output:-
Maximum Speed: 120
Use of super with methods:
/* Base class Person */
class Person
{
void message()
{
System.out.println("This is person class");
}
}
/* Subclass Student */
class Student extends Person
{
void message()
{
System.out.println("This is student class");
}
// Note that display() is only in Student class
void display()
{
// will invoke or call current class message() method
message();
// will invoke or call parent class message() method
super.message();
}
}
/* Driver program to test */
class Test
{
public static void main(String args[])
{
Student s = new Student();
// calling display() of Student
s.display();
}
}
Output:-
This is student class
This is person class
3. Use of super with constructors:
class Person
{
Person()
{
System.out.println("Person class Constructor");
}
}
/* subclass Student extending the Person class */
class Student extends Person
{
Student()
{
// invoke or call parent class constructor
super();
System.out.println("Student class Constructor");
}
}
/* Driver program to test*/
class Test
{
public static void main(String[] args)
{
Student s = new Student();
}
}
Output:-
Person class Constructor
Student class Constructor
What can we use SUPER for?
Accessing Superclass Members
If your method overrides some of its superclass's methods, you can invoke the overridden method through the use of the keyword super like super.methodName();
Invoking Superclass Constructors
If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Look at the code below:
class Creature {
public Creature() {
system.out.println("Creature non argument constructor.");
}
}
class Animal extends Creature {
public Animal (String name) {
System.out.println("Animal one argument constructor");
}
public Animal (Stirng name,int age) {
this(name);
system.out.println("Animal two arguments constructor");
}
}
class Wolf extends Animal {
public Wolf() {
super("tigerwang",33);
system.out.println("Wolf non argument constructor");
}
public static void main(string[] args) {
new Wolf();
}
}
When creating an object,the JVM always first execute the constructor in the class
of the top layer in the inheritance tree.And then all the way down the inheritance tree.The
reason why this is possible to happen is that the Java compiler automatically inserts a call
to the no-argument constructor of the superclass.If there's no non-argument constructor
in the superclass and the subclass doesn't explicitly say which of the constructor is to
be executed in the superclass,you'll get a compile-time error.
In the above code,if we want to create a Wolf object successfully,the constructor of the
class has to be executed.And during that process,the two-argu-constructor in the Animal
class is invoked.Simultaneously,it explicitly invokes the one-argu-constructor in the same
class and the one-argu-constructor implicitly invokes the non-argu-constructor in the Creature
class and the non-argu-constructor again implicitly invokes the empty constructor in the Object
class.
Constructors
In a constructor, you can use it without a dot to call another constructor. super calls a constructor in the superclass; this calls a constructor in this class :
public MyClass(int a) {
this(a, 5); // Here, I call another one of this class's constructors.
}
public MyClass(int a, int b) {
super(a, b); // Then, I call one of the superclass's constructors.
}
super is useful if the superclass needs to initialize itself. this is useful to allow you to write all the hard initialization code only once in one of the constructors and to call it from all the other, much easier-to-write constructors.
Methods
In any method, you can use it with a dot to call another method. super.method() calls a method in the superclass; this.method() calls a method in this class :
public String toString() {
int hp = this.hitpoints(); // Calls the hitpoints method in this class
// for this object.
String name = super.name(); // Calls the name method in the superclass
// for this object.
return "[" + name + ": " + hp + " HP]";
}
super is useful in a certain scenario: if your class has the same method as your superclass, Java will assume you want the one in your class; super allows you to ask for the superclass's method instead. this is useful only as a way to make your code more readable.
The super keyword can be used to call the superclass constructor and to refer to a member of the superclass
When you call super() with the right arguments, we actually call the constructor Box, which initializes variables width, height and depth, referred to it by using the values of the corresponding parameters. You only remains to initialize its value added weight. If necessary, you can do now class variables Box as private. Put down in the fields of the Box class private modifier and make sure that you can access them without any problems.
At the superclass can be several overloaded versions constructors, so you can call the method super() with different parameters. The program will perform the constructor that matches the specified arguments.
public class Box {
int width;
int height;
int depth;
Box(int w, int h, int d) {
width = w;
height = h;
depth = d;
}
public static void main(String[] args){
HeavyBox heavy = new HeavyBox(12, 32, 23, 13);
}
}
class HeavyBox extends Box {
int weight;
HeavyBox(int w, int h, int d, int m) {
//call the superclass constructor
super(w, h, d);
weight = m;
}
}
super is a keyword. It is used inside a sub-class method definition to call a method defined in the superclass. Private methods of the superclass cannot be called. Only public and protected methods can be called by the super keyword. It is also used by class constructors to invoke constructors of its parent class.
Check here for further explanation.
As stated, inside the default constructor there is an implicit super() called on the first line of the constructor.
This super() automatically calls a chain of constructors starting at the top of the class hierarchy and moves down the hierarchy .
If there were more than two classes in the class hierarchy of the program, the top class default constructor would get called first.
Here is an example of this:
class A {
A() {
System.out.println("Constructor A");
}
}
class B extends A{
public B() {
System.out.println("Constructor B");
}
}
class C extends B{
public C() {
System.out.println("Constructor C");
}
public static void main(String[] args) {
C c1 = new C();
}
}
The above would output:
Constructor A
Constructor B
Constructor C
The super keyword in Java is a reference variable that is used to refer to the immediate parent class object.
Usage of Java super Keyword
super can be used to refer to the immediate parent class instance variable.
super can be used to invoke the immediate parent class method.
super() can be used to invoke immediate parent class constructor.
There are a couple of other uses.
Referencing a default method of an inherited interface:
import java.util.Collection;
import java.util.stream.Stream;
public interface SkipFirstCollection<E> extends Collection<E> {
#Override
default Stream<E> stream() {
return Collection.super.stream().skip(1);
}
}
There is also a rarely used case where a qualified super is used to provide an outer instance to the superclass constructor when instantiating a static subclass:
public class OuterInstance {
public static class ClassA {
final String name;
public ClassA(String name) {
this.name = name;
}
public class ClassB {
public String getAName() {
return ClassA.this.name;
}
}
}
public static class ClassC extends ClassA.ClassB {
public ClassC(ClassA a) {
a.super();
}
}
public static void main(String[] args) {
final ClassA a = new ClassA("jeff");
final ClassC c = new ClassC(a);
System.out.println(c.getAName());
}
}
Then:
$ javac OuterInstance.java && java OuterInstance
jeff

Categories

Resources