Java Inheritance and Constructor Arguments - java

I am amateur in Java please help me.
I have a class: Account
public class Account {
protected String fullName;
protected String accontNumber;
protected String password;
protected int balance;
public Account(String name, String acc_num, String pass, int b){
fullName = name;
accontNumber = acc_num;
password = pass;
balance = b;
}
}
and I going to create a new class Account2 that inherit from Account
public class Account2 extends Account{
public Account2(String l){
String[] temp = l.split(",");
super.fullName = temp[0];
super.accontNumber = temp[1];
super.password = temp[2];
super.balance = Integer.parseInt(temp[3]);
}
}
But I receive an error message that say: Actual and formal argument list are differ in length
how can I solve this problem?

When the base class has a non-default constructor (one or more parameter), the derived class must call the base class constructor in its constructor with super(paramters). And also notice for constructor, you must have the first line with the super statement, so you must declare a construct with the same parameter, or correctly pass in the parameter within one line, though this is not recommended:
public Account2(String l) {
super(l.split(",")[0],l.split(",")[1],l.split(",")[2],Integer.parseInt(l.split(",")[3]));
}

do like this
public class Account2 extends Account{
public Account2(String l){
super(l.split(",")[0],l.split(",")[1],l.split(",")[2],Integer.parseInt(l.split(",")[3]))
}
}

You haven't placed the super constructor call. So by default it will try to pick super() i.e. no-argument constructor which is not present in Account class

Your current subclass constructor sets the values of the superclass parameters after superclass construction. If you would like to keep that approach, add a no-arg constructor to the superclass that sets default values.
It would be better to use setters rather than accessing the fields directly.

IMHO in this case you sholudn't use a constructor. Create a static method that takes your String input, validates it, splits it into some logical parts and then uses "normal" constructor to create an object:
class Account2 extends Account {
Account2(String name, String acc_num, String pass, int b) {
super(name, acc_num, pass, b);
}
public static Account2 createFromString(String input) {
String[] temp = l.split(",");
if (temp.length != 4) {
throw new RuntimeException("...");
}
return new Account2(temp[0], temp[1], temp[2], Integer.parseInt(temp[3]));
}
}
Your code will be a lot cleaner in my personal opinion:
Account2 acc1 = new Account2("abc", "def", "ghi", 2);
Account2 acc2 = Account2.createFromString("abc,def,ghi,2");

The probelm:
Actual and formal argument list are differ in length
To understand this, a basic understanding of constructors and their behavior under inheritance will help you.
When we define a class without constructors, the compiler inserts a zero argument constructor by itself.
If we write our own constructor with some argument then this default constructor is not inserted by compiler and if required, it has to be added explicitly.
When an instance of a subclass is created , there is an implicit call (very first thing to get executed during constructor invocation) to the superclass constructor by default.
So, if there is no default constructor in superclass (which will be the case when we define our own custom constructor with argument), the compiler will complain.
To get around this, you need to call the constructor with argument as very first line in the subclass constructor or define a default constructor explicitly.

Related

Keyword 'this' with parenthesis that receive parameters in Java 'this(param1,param2)'. Can it be used in setters?

Java allows to summarize this.classVar = parameter; this.classVar2 = parameter2; expressions to this(parameter, parameter2). At least used in a constructor.
But this code doesn't work when I change from the former way (commented in the code) to the latter way in a setter:
class Client {
String nombre, apellidos, residencia;
double comision;
void setClient(String nombre, String apellidos, String residencia, double comision){
this(nombre, apellidos, residencia, comision);
//this.nombre = nombre;
//this.apellidos = apellidos;
//this.residencia = residencia;
//this.comision = comision;
}
}
Error says:
"call to this must be first statement in the constructor.
Constructor in class Client cannot be applied to given types.
required: no arguments
<p>found: String, String, String, double
<p>reason: actual and formal argument list differ in length" (I haven't created one, just left the default).
So, is this way of using 'this' only valid for constructors, and therefore not suitable for setters? Does it require to explicitly code the constructor (if so, why?)?
Java allows to summarize this.classVar = parameter; this.classVar2 = parameter2; expressions to this(parameter, parameter2).
No, it doesn't. You still have to code the this.classVar = parameter; this.classVar2 = parameter2; somewhere. All this(parameter, parameter2) does is call a constructor (which would have to have the this.classVar = parameter; this.classVar2 = parameter2; code in it, if those parameters were going to be written to those fields).
You can't call the constructor from a setter. You can only call a constructor from within a constructor. It's used to consolidate logic in a single constructor even when you have more than one with varying parameters, for example:
public MyContainer(int size) {
this.size = size;
}
public MyContainer() {
this(16);
}
There, the zero-parameters version of the MyContainer constructor calls the single-parameter version, passing it 16 for the size parameter.
this(nombre, apellidos, residencia, comision) doesn't "summarize" anything.
It's just a way to call another constructor in the class from a constructor.
There is no way to "summarize" anything
this(/* zero or more args */);
This is a constructor call. You can use it from one constructor to refer to another (for lack of a better name, 'constructor chaining').
You cannot do the same thing from a normal method. If you want to create an object from within a normal method, you use the same syntax as you'd use an an external user of the class:
new MyClass(/* args */);
From your code, it doesn't look like this is the approach you'd want to take.

can you use default and parameter constructor at the same time?

I have been assigned to make a class using both default and parameter constructor but the thing is, is that even possible? I don't get how it can even work..both are supposed to assign values to variables
Borrowed from this answer from #bohemian
public class Person
...
public Person() {
this("unknown", 0); // you can call another constructor
}
public Person(String nm, int ag) {
name = nm;
age = ag;
}
...
}
In this example if the no-args constructor is called then unknown and 0 will be passed to the other constructor
When you define another constructor in your class, you do not get the "usual" default constructor (public and without arguments) anymore.
However, you can add it back in:
class MyClass{
MyClass(String param){} // custom constructor
MyClass(){} // bring back the non-arg one
}
Of course, when creating an object instance using new you have to choose which one to call (you cannot have both):
MyClass instanceA = new MyClass("a string");
MyClass instanceB = new MyClass();
The constructors can call each-other (using this(parameters)) or shared methods if there is common functionality in them that you want to keep in one place.
Actually you can't do that in Java, by definition.JLS §8.8.9, http://docs.oracle.com/javase/specs/jls/se8/html/jls-8.html#jls-8.8.9 says, "If a class contains no constructor declarations, then a default constructor is implicitly declared." So as soon as you add any constructor declaration, even a no-arg constructor, you don't get a default constructor.

Does a subclass in Java need a constructor if there is one for the superclass? [duplicate]

What exactly is a default constructor — can you tell me which one of the following is a default constructor and what differentiates it from any other constructor?
public Module() {
this.name = "";
this.credits = 0;
this.hours = 0;
}
public Module(String name, int credits, int hours) {
this.name = name;
this.credits = credits;
this.hours = hours;
}
Neither of them. If you define it, it's not the default.
The default constructor is the no-argument constructor automatically generated unless you define another constructor. Any uninitialised fields will be set to their default values. For your example, it would look like this assuming that the types are String, int and int, and that the class itself is public:
public Module()
{
super();
this.name = null;
this.credits = 0;
this.hours = 0;
}
This is exactly the same as
public Module()
{}
And exactly the same as having no constructors at all. However, if you define at least one constructor, the default constructor is not generated.
Reference: Java Language Specification
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Clarification
Technically it is not the constructor (default or otherwise) that default-initialises the fields. However, I am leaving it the answer because
the question got the defaults wrong, and
the constructor has exactly the same effect whether they are included or not.
A default constructor is created if you don't define any constructors in your class. It simply is a no argument constructor which does nothing. Edit: Except call super()
public Module(){
}
A default constructor is automatically generated by the compiler if you do not explicitly define at least one constructor in your class. You've defined two, so your class does not have a default constructor.
Per The Java Language Specification Third Edition:
8.8.9 Default Constructor
If a class contains no constructor
declarations, then a default
constructor that takes no parameters
is automatically provided...
Hi. As per my knowledge let me clear the concept of default constructor:
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.
I read this information from the Java Tutorials.
Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.
The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.
Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).
public class Cube1 {
int length;
int breadth;
int height;
public int getVolume() {
return (length * breadth * height);
}
Cube1() {
length = 10;
breadth = 10;
height = 10;
}
Cube1(int l, int b, int h) {
length = l;
breadth = b;
height = h;
}
public static void main(String[] args) {
Cube1 cubeObj1, cubeObj2;
cubeObj1 = new Cube1();
cubeObj2 = new Cube1(10, 20, 30);
System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
}
}
General terminology is that if you don't provide any constructor in your object a no argument constructor is automatically placed which is called default constructor.
If you do define a constructor same as the one which would be placed if you don't provide any it is generally termed as no arguments constructor.Just a convention though as some programmer prefer to call this explicitly defined no arguments constructor as default constructor. But if we go by naming if we are explicitly defining one than it does not make it default.
As per the docs
If a class contains no constructor declarations, then a default constructor with no formal parameters and no throws clause is implicitly declared.
Example
public class Dog
{
}
will automatically be modified(by adding default constructor) as follows
public class Dog{
public Dog() {
}
}
and when you create it's object
Dog myDog = new Dog();
this default constructor is invoked.
default constructor refers to a constructor that is automatically generated by the compiler in the absence of any programmer-defined constructors.
If there's no constructor provided by programmer, the compiler implicitly declares a default constructor which calls super(), has no throws clause as well no formal parameters.
E.g.
class Klass {
// Default Constructor gets generated
}
new Klass(); // Correct
-------------------------------------
class KlassParameterized {
KlassParameterized ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassParameterized(); //// Wrong - you need to explicitly provide no-arg constructor. The compiler now never declares default one.
--------------------------------
class KlassCorrected {
KlassCorrected (){ // No-arg Constructor
/// Safe to Invoke
}
KlassCorrected ( String str ) { //// Parameterized Constructor
// do Something
}
}
new KlassCorrected(); /// RIGHT -- you can instantiate
If a class doesn't have any constructor provided by programmer, then java compiler will add a default constructor with out parameters which will call super class constructor internally with super() call. This is called as default constructor.
In your case, there is no default constructor as you are adding them programmatically.
If there are no constructors added by you, then compiler generated default constructor will look like this.
public Module()
{
super();
}
Note: In side default constructor, it will add super() call also, to call super class constructor.
Purpose of adding default constructor:
Constructor's duty is to initialize instance variables, if there are no instance variables you could choose to remove constructor from your class. But when you are inheriting some class it is your class responsibility to call super class constructor to make sure that super class initializes all its instance variables properly.
That's why if there are no constructors, java compiler will add a default constructor and calls super class constructor.
When we do not explicitly define a constructor for a class, then java creates a default constructor for the class. It is essentially a non-parameterized constructor, i.e. it doesn't accept any arguments.
The default constructor's job is to call the super class constructor and initialize all instance variables. If the super class constructor is not present then it automatically initializes the instance variables to zero. So, that serves the purpose of using constructor, which is to initialize the internal state of an object so that the code creating an instance will have a fully initialized, usable object.
Once we define our own constructor for the class, the default constructor is no longer used. So, neither of them is actually a default constructor.
When you don’t define any constructor in your class, compiler defines default one for you, however when you declare any constructor (in your example you have already defined a parameterized constructor), compiler doesn’t do it for you.
Since you have defined a constructor in class code, compiler didn’t create default one. While creating object you are invoking default one, which doesn’t exist in class code. Then the code gives an compilation error.
When you create a new Module object, java compiler add a default constructor for you because there is no constructor at all.
class Module{} // you will never see the default constructor
If you add any kind of constructor even and non-arg one, than java thing you have your own and don't add a default constructor anymore.
This is an non-arg constructor that internelly call the super() constructor from his parent class even you don't have one. (if your class don't have a parent class than Object.Class constructor will be call)
class Module{
Module() {} // this look like a default constructor but in not.
}
A default constructor does not take any arguments:
public class Student {
// default constructor
public Student() {
}
}
I hope you got your answer regarding which is default constructor.
But I am giving below statements to correct the comments given.
Java does not initialize any local variable to any default value. So
if you are creating an Object of a class it will call default
constructor and provide default values to Object.
Default constructor provides the default values to the object like 0,
null etc. depending on the type.
Please refer below link for more details.
https://www.javatpoint.com/constructor

How do you define a constructor in Java?

I'm new to Java so I'm not sure what exactly is the problem with my code. I keep on getting a Unresolved compilation problem: The constructor Student() is undefined. I have been working on it for hours now but I'm not sure what the problem is. I would appreciate the help. Thanks!
You created your constructor correctly:
public Student (String n, char g, Date b, Preference p){
name = n;
gender = g;
birthDay = b;
pref = p;
}
However, this constructor only works with all of those arguments given. You're trying to make a Student object with no parameters into the constructor. This case is called the default constructor.
To make such a constructor, you'd do:
public Student (){
//some default initializations
}
You are instantiating a student using
new Student()
Which is wrong because you have not yet defined a constructor that takes no parameters.
You can fix it by either defining a new constructor
public Student(){
//Set default values here
}
Or by using the constructor you already have.
Student bestStudent = new Student("Bryan", 'm', ...);
Java provides a default constructor for a class when you do not define one ( in this case Student() ) . However, since defined the constructor Student( String s, char c, Date d, Preference p ) this default constructor is not automatically provided.
You now have to either use the constructor you specified. Or implement an constructor in the Student class that accepts no parameters
public Student() { }
You can use this to call the other constructor with your default variables.
public Student() {
this("", '', null, null); //Assuming you code is made to handle such a situation
}
You are calling new Student() with no arguments. This is called a default constructor. You don't have to specify a default constructor if there are no other constructors. But if you have another constructor that takes arguments, then you have to specify it.
You simply need to add this to your Student class.
public Student(){
}
You need to pass a value for n, g, b, p.
So new Student("hi", 'a', new Date(), myPreference)
when you initialize your variables in Student() they should have modifiers:
private String name;
private char gender;
private Boolean matched;
etc; this might be the cause for your error.
Add another constructor that is called a no-argument constructor to your student class. Because in the for loop you are using one without any arguments. And you have not defined it in the Student class.
Simply add the following lines.
public Student() {
}
Example: If you have class with name Main
So you can define constructor for this class Like:
Main(){
}
For more details about constructors please refer to this link.

Why Is This Method Invalid?

It says that public user number is an invalid method. It states that the part of the code is invalid and requires a return type.
public UserNumber(){
super();
randy = new java.util.Random();
} //=======================
What do I do to fix it?
In Java method has to have return type (int, Integer, Random) or void if it is not intended to return anything. Add void after public.
public void UserNumber() {
...
}
There is a chance you wanted to create a class constructor, but then its name has to be the same as the class name. For example:
public class UserNumber {
private final Random randy;
public UserNumber() {
super();
randy = new Random();
}
}
(in that case calling super() can be omitted - it is performed anyway)
Please provide full code of this class.
Unless you class is called UserNumber, you need to add a return type to the method declaration:
public void UserNumber(){
randy = new java.util.Random();
}
void as return type, since that method won't return anything.
If you, instead, wanted to make it a constructor, the name of the constructor must be the same of the class.
class UserNumber extends ...{
public UserNumber(){
super();
randy = new java.util.Random();
}
...
}
Constructor name should be identical as your class name!
public class UserNumber {
public UserNumber() {
super();
randy = new java.util.Random();
}
}
To invoke this special method use: new UserNumber() - this is all :)
More:
Java: How can a constructor return a value?
Add void after public. Every method needs a return type and this will set it to return nothing.
You are missing the return type. It must be Whether void, int or any object type.
The call to super() makes me think that this is supposed to be a constructor. Your class must be called UserNumber
In this case you do not need a return type, since constructors always return a new instance of the class.
If it's not a constructor, get rid of the call to super(), as you may only call that in a constructor. Also make sure that the class you're extending has a parameterless constructor.
I think1 that the real problem is that you are confused over the difference between a method and a constructor, and you are trying to use a constructor as if it was a method.
Your UserNumber so-called method is actually declared (properly!) as a constructor1. The way to use is as a constructor is as follows:
UserNumber myNum = new UserNumber();
I suspect you are trying to call it like:
... = UserNumber();
... and that is going to fail, saying that UserNumber is an invalid method. A Java constructor is invoked using new.
There are 3 clues that say to me that the OP's code is intended to be a constructor:
The super() syntax is only valid in a constructor.
A method declaration requires a return type AND a method name. This has only one identifier before the parameter list.
You've used an identifier that should be a class name (according to the Java identifier rules).
1 - I can't be sure, because you didn't show us the line with the syntax error on it. Or if you did, then the real problem is somewhere else ... in code that you haven't shown us.

Categories

Resources