Setting final value in a constructor - java

I have the following problem. I have two classes - one is the base class and the pther is inheriting it. So in the parent class is an abstract class and it consists three fields - String name, String adress and int age. However in my task it says the value for age has to be set by default to be 25 years. My question is - How do implement this value with the help of inherited method setAge() in the constructor of the inherited class?
My abstract constructor looks like this:
public Student(String name, String adress, int age){
this.setName(name);
this.setAdress(adress);
this.setAge(age);
}
and setter:
public void setAge(int age){
this.age = age;
}
How do I do the implementation in the inherited class by using a default value?

If the superclass constructor takes three parameters in its constructor, and you have subclass with a constructor with only two parameters, you can call super to pass the two arguments plus a third default value to the constructor of the superclass.
public abstract class Person
{
// Constructor
public Person() ( String name, String address, int age )
{ …
And subclass.
public abstract class Student
{
// Constructor
public Person() ( String name, String address )
{
super( name , address , 25 ) ; // Default age of 25 for new `Student` objects.
…
This is a silly example as defaulting a person’s age would not happen in real work. But the concepts demonstrated are sound.

Related

It shows an error when executing the inheritance constructors "actual and formal argument lists differ in length" [duplicate]

I have 2 subclasses: Staff, Student
they belong to superclass Person.
Here is the code(tasks) which is given by my teacher:
public class Person
{
private String name;
private int yearOfBirth;
/**
* Create a person with given name and age.
*/
Person(String name, int yearOfBirth)
{
this.name = name;
this.yearOfBirth = yearOfBirth;
}
}
class Student extends Person
{
private String SID; // student ID number
/**
* Create a student with no parameters.
*/
Student()
{
//task.
}
}
public class Staff extends Person
{
private String roomNumber;
/**
* Construct a staff member with field values and no pamaeters.
*/
public Staff()
{
//task
}
}
I don't know what can I type in order to create an object without parameter.
It always appears an error like: constructor Person in class Person cannot be applied to given types; required: java.lang.String,int;
I have checked online that there are 2 ways to solve the problem:
add a default value in the superclass: Person()//without parameter.
In the subclass Student:
Student()
{
Person astudent = new Student() //I guess.
}
add a super() in the subclass:
Student()
{
super("xxx")//I guess.
}
I don't know what to do. I an a starter in learning BlueJ.
Hope anyone can help me. Thank you very much.
Since your superclass Person doesn't have a default constructor, in your subclasses (Student and Staff), you must call the superclass constructor as the first statement.
You should define your sub-class constructors like this:
Student() {
super("a_string_value", an_int_value);// You have to pass String and int values to superclass
}
Staff() {
super("a_string_value", an_int_value); // You have to pass String and int values to super class
}
the first thing a constructor will do, is call the constructor (with same arguments) of the super class.
Person does not have a no-argument constructor, so, you must change your code in one of next two ways:
Student(String name, int yearOfBirth)
{
//task.
}
or
Student()
{
super("", 0);
//task.
}
and the same goes for Staff
Add super(NAME_IN_STRING_TYPE,YEAR_OF_BIRTH_IN_INT_TYPE); as a first statement in your subclasse's constructor like
Student constructor
Student()
{
super("name", 1970); // String,int arguments passed
//task.
}
Staff constructor
Staff()
{
super("name", 1970); // String,int arguments passed
//task.
}
This is needed since there is no default no-arg constructor in the base class. You have to explicitly define a no-arg constructor in base class or you need to instruct the compiler to call the custom constructor of the base class.
Note : Compiler will not add default no-arg constructor in a class if it has a user defined constructor. It will add the default no-arg constructor only when there is no constructor defined in the class.
Try this:
Student(String name, int yearOfBirth) {
super(name, yearOfBirth);
// task...
}
Reason: you dont have a default constructor at your superclass. So you have to call super() at the first position in your subclass constructor.
To construct instance of Student you need to do actions neccesary to construct Person first. There is only one way to construct Person - two-arg constructor. That means you have to change Student like:
public Student() {
super("someName", 1950); //first values came to my mind
}
Although you should be aware that Student should behave exactly like Person if treated as Person, i.e. have age and name. So actually I'd recommend to change Student constructor to include name and age there.
If you want to create an object of child class (ie Staff and Student) without passing parameters then you can create an additional constructor without parameters in the parent class (ie Person class) as below.
public class Person
{
private String name;
private int yearOfBirth;
/**
* Create a person with given name and age.
*/
Person(String name, int yearOfBirth)
{
this.name = name;
this.yearOfBirth = yearOfBirth;
}
// additional constructor without parameter
Person(){
// add your code here
}
}
now below code will work without any error.
Staff stf = new Staff();
Student std = new Student();
for constructor no param you should have two constructors like
public class Student {
Student(String name , int dateOfBirth)
{
super(name,dateOfBirth)
}
Student()
{
//task.
}
}
also same for other class
student should not extend person.
bcoz, if we create obj for student, person’s constructor will be called automatically.

Implicit super constructor Person() is undefined. Must explicitly invoke another constructor

Im receiving that error when trying create a constructor for the second class. Do I need to use the same parameters for the second class as the first class?
class Person {
private String name;
private String gender;
private int phone;
protected Person(String n, String g, int p)
{name = n; gender = g; phone = p;}
public String toString(){return name +" "+gender+" "+phone;}
}
class Student extends Person {
private String subject;
private int sNumber;
protected Student(String s, int sn){subject = s; sNumber = sn;}
}
class Lecturer extends Person {
private String Department;
private int staffNo;
public Lecturer(String d, int stfNo){Department = d; staffNo = stfNo;}
}
Every extended class calls the super constructor first. In your Person class you have defined only a non default constructor therefore there is no default constructor.
Either provide a default constructor (constructor without any parameters) in Person or call the super constructor explicitly with super(name, gender, phone)
When compiled, your compiler will add super() as the first line of your childs constructor searching for the parent non arg constructor.
Since your parent class already has one using params, no default no arg constructor will be created at compile time.
Two solutions :
Add super(string,string,int) giving it the right parameters as the first line of your childs constructor
Create a Person() constructor taking no arguments so that super() finds something to call at compilation time.
If a class extends another class, it must call the constructor of that extended class.
Since you specified a constructor for Person you need to call it in Student and Lecturer as the first statement:
protected Student(String s, int sn, String n, String g, int p)
{
super(n, g, p);
subject = s;
sNumber = sn;
}
You might not have seen this error before, since the compiler automatically adds super(); as the first statement. Since this constructor does not exists (you specified your own) this does not work.
If you don't call the constructor of the super class you never initialize it.

Java cannot find parent class

I have this class, Person:
public class Person{
String firstname;
String lastname;
public Person(String fname, String lname){
}
public String toString(){
}
}
And this subclass, Student:
public class Student extends Person{
Student(){
super();
}
int studentID;
int level;
public Student(String fName, String lName, int gLevel){
}
public int getLevel(){
}
public String toString(){
}
}
When I compile in DrJava, I get the error:
cannot find symbol
symbol : constructor Person()
location: class Person
I'm not sure what the problem is. It's my understanding that the use of the super() constructor should resolve this problem, and that it's not even necessary in the code. My code matches any example I've seen online demonstrating inheritance in Java, but I'm continuing to get this error.
Calling super(); supposes there's a default constructor in the Person class, while there isn't such, since you have a non-default one.
You have to either provide explicitly the default constructor:
public Person() { }
or pass two parameters in the super statement:
super("Firstname", "Lastname");
This happens because there is no zero argument constructor or default constructor present in your Person Class.
Since Every child constructor calls Parent Class Constructor in it's 1 line with super() implicitly So same way Student Class's Constructor Called and it was unable to find out default Constructor in Parent Class.
Why Java Compiler doesn't provide default constructor automatically/implicitly Since parameterised Constuctor is already present in your Parent Class

java constructor in class cannot be applied to given types

I have 2 subclasses: Staff, Student
they belong to superclass Person.
Here is the code(tasks) which is given by my teacher:
public class Person
{
private String name;
private int yearOfBirth;
/**
* Create a person with given name and age.
*/
Person(String name, int yearOfBirth)
{
this.name = name;
this.yearOfBirth = yearOfBirth;
}
}
class Student extends Person
{
private String SID; // student ID number
/**
* Create a student with no parameters.
*/
Student()
{
//task.
}
}
public class Staff extends Person
{
private String roomNumber;
/**
* Construct a staff member with field values and no pamaeters.
*/
public Staff()
{
//task
}
}
I don't know what can I type in order to create an object without parameter.
It always appears an error like: constructor Person in class Person cannot be applied to given types; required: java.lang.String,int;
I have checked online that there are 2 ways to solve the problem:
add a default value in the superclass: Person()//without parameter.
In the subclass Student:
Student()
{
Person astudent = new Student() //I guess.
}
add a super() in the subclass:
Student()
{
super("xxx")//I guess.
}
I don't know what to do. I an a starter in learning BlueJ.
Hope anyone can help me. Thank you very much.
Since your superclass Person doesn't have a default constructor, in your subclasses (Student and Staff), you must call the superclass constructor as the first statement.
You should define your sub-class constructors like this:
Student() {
super("a_string_value", an_int_value);// You have to pass String and int values to superclass
}
Staff() {
super("a_string_value", an_int_value); // You have to pass String and int values to super class
}
the first thing a constructor will do, is call the constructor (with same arguments) of the super class.
Person does not have a no-argument constructor, so, you must change your code in one of next two ways:
Student(String name, int yearOfBirth)
{
//task.
}
or
Student()
{
super("", 0);
//task.
}
and the same goes for Staff
Add super(NAME_IN_STRING_TYPE,YEAR_OF_BIRTH_IN_INT_TYPE); as a first statement in your subclasse's constructor like
Student constructor
Student()
{
super("name", 1970); // String,int arguments passed
//task.
}
Staff constructor
Staff()
{
super("name", 1970); // String,int arguments passed
//task.
}
This is needed since there is no default no-arg constructor in the base class. You have to explicitly define a no-arg constructor in base class or you need to instruct the compiler to call the custom constructor of the base class.
Note : Compiler will not add default no-arg constructor in a class if it has a user defined constructor. It will add the default no-arg constructor only when there is no constructor defined in the class.
Try this:
Student(String name, int yearOfBirth) {
super(name, yearOfBirth);
// task...
}
Reason: you dont have a default constructor at your superclass. So you have to call super() at the first position in your subclass constructor.
To construct instance of Student you need to do actions neccesary to construct Person first. There is only one way to construct Person - two-arg constructor. That means you have to change Student like:
public Student() {
super("someName", 1950); //first values came to my mind
}
Although you should be aware that Student should behave exactly like Person if treated as Person, i.e. have age and name. So actually I'd recommend to change Student constructor to include name and age there.
If you want to create an object of child class (ie Staff and Student) without passing parameters then you can create an additional constructor without parameters in the parent class (ie Person class) as below.
public class Person
{
private String name;
private int yearOfBirth;
/**
* Create a person with given name and age.
*/
Person(String name, int yearOfBirth)
{
this.name = name;
this.yearOfBirth = yearOfBirth;
}
// additional constructor without parameter
Person(){
// add your code here
}
}
now below code will work without any error.
Staff stf = new Staff();
Student std = new Student();
for constructor no param you should have two constructors like
public class Student {
Student(String name , int dateOfBirth)
{
super(name,dateOfBirth)
}
Student()
{
//task.
}
}
also same for other class
student should not extend person.
bcoz, if we create obj for student, person’s constructor will be called automatically.

Inheritance and Constructors in Java

So, I'm working on a homework assignment, and I'm having a hard time following some of the directions, I've pasted the assignment below:
Create a hierarchy of five classes, plus one class included as a variable inside:
Person has four String variables: name, address, phone, email
Student is a subclass to Person and has one additional int variable status which takes values of 1, 2, 3, or 4 representing freshman, sophomore, junior, senior
MyDate has three int variables for year, month, and day
Employee is a subclass to Person and has one String variable office, one int variable for salary, and one MyDate variable for dateHired
Staff is a subclass to Employee and has one additional String variable for title
Faculty is a subclass to Employee and has one additional String variable for rank which takes values of Professor, Associate Professor, Assistant Professor, Instructor, and Adjunct. The data for all six classes should be private.
As for methods, you can skip the normal setters and getters if you write a single constructor that has parameters for all data and override the toString( ) method. Constructors of subclasses should use the super class constructor. The toString( ) methods of subclasses should use the toString( ) method of their super class.
The part that throws me for a loop is the idea that a single constructor can be written that will cover all the necessary parameters for the setters and getters instead of writing them in each sub-class. Is this possible? And how so?
You need to use the constructor of the superclass whilst creating the subclass. So it should be:
public class Staff extends Employee {
private String title;
public Staff(String name, String address, String phone, String email, int status, String title) {
super(name, address, phone, email, status);
this.title = title;
}
}
Use the super(/*params of super class*/) to invoke the constructor of the super class and instantiate the inherited attributes. Note that you can only call a superclass constructor as the first statement of a constructor. If you don't call a superclass constructor explicitly, a call to super() (the default constructor of the superclass) is inserted automatically by the Java compiler.
For calling the parent class's toString() use:
public String toString() {
return super.toString() + " ,title : " this.title;
}
Similarly write the constructors and toString() methods of all classes.
As for methods, you can skip the normal setters and getters if you write a single constructor that has parameters for all data and override the toString( ) method.
I think the directions mean that each class you write can have a single constructor that takes parameters for all of its data. Taking the MyDate constructor for example:
public MyDate(int year, int month, int day) {
...
}
And likewise override toString() to report all that information.
Instead of writing
public class A {
private int b;
private int c;
public void setB(int b) {this.b = b;}
public int getB() {return b;}
// same for c
}
you allowed to code
public class A {
private int b;
private int c;
public A(int b, int c) {
this.b = b;
this.c = c;
}
#Override
public String toString() {
return "[b = " + b + ", c = " + c + "]";
}
(The implementation of toString() is just an example, it just needs to print the states of all fields)
This is what you can do
Person(String name,String address,String phone,String email){
//Person constructor
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
}
public String toString(){
//toString method
return "Name: "+name+" Address: "+address+" Phone: "+phone+" Email: "+email;
}

Categories