Class Declarations, Constructors and toString methods for all the classes - java

Question:
Implement a super class Person. Make two classes, Student and Instructor
that inherit from Person. A person has a name and a year of birth. A student
has major and the instructor has a salary. Write the class declarations, the
constructors, and the methods to String for all classes. Write a test program
that tests these classes and methods.
This may not be a complicated one but i'm a beginner in java. Please help me.
I'm getting the following error at the both the constructors 'student()' and 'instructor()'.
"constructor Person in class Person cannot be applied to given types;
required: String,int
found: no arguments
reason: actual and formal argument lists differ in length."
Here's my code:
package One;
class Person{
String name;
int yob;
Person(String s, int d){
name = s;
yob = d;
}
#Override
public String toString(){
return "Name: "+name+"\n Year of Birth: "+yob;
}
}
class Student extends Person{
String major;
Student(String s){
major = s;
}
#Override
public String toString(){
return "The student did his majors in "+major;
}
}
class Instructor extends Person{
int salary;
Instructor(int a){
salary = a;
}
#Override
public String toString(){
return String.format("The salary is ",salary);
}
}
public class Test {
public static void main(String[] args) {
Person p = new Person("Stephen", 1991);
System.out.println(p);
}
}
Thanks in advance.

In your code, the classes Student and Instructor derive from Person. This means that any constructor parameters needed by the base class are also needed by the derived class. When you create a Student, how will the compiler know what to put in the parameters of the Person constructor?
So the code should be like this:
// Student constructor
Student(String majorParam, String nameParam, int yobParam)
{
super(nameParam, yobParam);
this.major = majorParam;
}
...
// Similarly, Instructor constructor
Instructor(int salaryParam, String nameParam, int yobParam)
{
super(nameParam, yobParam);
salary = salaryParam;
}
Notice how we are transferring the constructor parameters required by the base class Person using the super constructor keyword. This always has to be the first line in the derived class constructor.
Then you can construct Student and Instructor as:
Student s = new Student("TheMajor", "TheName", 42);
Instructor i = new Instructor(1000, "TheName", 42);

There is no empty constructor in Person class, so you have to create that and it should work perfectly. Don't forget that super() is called by default unless explicitly called.

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.

Access property after inheriting from an abstract class Java

I cannot access a field of a class that is a concrete type inheriting from an abstract class.
In Java I create a class of External student that extends Student
*/
public class ExternalStudent extends Student {
String currentSchool;
public ExternalStudent(String name, Integer age, String studentIdentifier, String currentSchool) {
super(name, age, studentIdentifier);
this.currentSchool = currentSchool;
}
}
where student is
public abstract class Student {
//Attributes
String studentIdentifier;
Integer age;
String name;
//Associations
List<Subject> subject = new ArrayList<Subject>();
PersonalDetails personaldetails;
//Methods
public void setSubject () {
this.subject.add(new Subject("Name"));
}
//Constructors
public Student(String name, Integer age, String studentIdentifier){
this.age = age;
this.name = name;
this.studentIdentifier = studentIdentifier;
}
}
and external student is set up by my class Application
public class ApplicationC {
//Attributes
private String personalStatement;
private String applicationForm;
//Associations
Registration registration;
Student student;
ApplicationTest applicationtest;
//Methods
public void setApplicationResult(String result){
this.applicationtest = new ApplicationTest(result);
}
//Constructor
public ApplicationC (String personalStatement, String name){
this.registration = new Registration();
this.student = new ExternalStudent("Tom",16,"78954","DHS");
}
}
I've set up a simple test class
public void testPostCondition() throws ParseException{
ApplicationC instance = new ApplicationC("test statement","test name");
instance.setApplicationResult("pass");
assertEquals("pass",instance.applicationtest.result);
instance.student.age = 16;
instance.student.studentIdentifier = "78954";
instance.student.name = "Tom";
instance.student.currentSchool = "test"; //Error as field does not exist
}
But I cannot access the current school of the student instance (who must be an externalStudent). How can I access this field in order to test my code?
In ApplicationC, the student field is declared with the Student class :
Student student;
Methods available on an objects relies on the declared type, not the object really instantiated.
And currentSchool is only declared in the subclass ExternalStudent.
So, you cannot access it in this way.
A workaround is downcasting Student to ExternalStudent :
((ExternalStudent)instance.student).studentIdentifier = "78954";
And generally, it is better to check the type of the instance before doing it :
if (instance.student instanceof ExternalStudent){
((ExternalStudent)instance.student).studentIdentifier = "78954";
}
As a general advice, in Java, you should favor the private modifier for fields and if you need to manipulate the base class and access to some fields specific to the subclass, you could define a method in the base class that returns null or Optional and override it in the subclass with the return of the field.
It avoids cast that may be error prone and that often are symptoms of a conception problem.
Your instance is an AplicationC,
So, "instance.student" is a "Student".
"Student" does not have the "currentSchool" property.
to get to it
* add "currentSchool" property to "Student"
or
* cast your "instance.student" to "ExternalStudent"
note: you will need to handle all the exceptions and over-head of casting etc'
Hope this helps

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