I am trying to write the Undergrad class which extends Students
here is the base class (Student)
public class Student{
private String name;
private int id;
private double gpa;
public Student(){
}
public Student(int id, String name, double gpa){
this.id = id;
this.name = name;
this.gpa = gpa;
}
public Student(int id, double gpa){
this(id, "", gpa);
}
public String getName(){
return name;
}
public int getId(){
return id;
}
public double getGPA(){
return gpa;
}
public void setName(String newName){
this.name = newName;
}
@Override
public String toString(){
return "Student:\nID: " + id + "\nName: " + name + "\nGPA: " + gpa;
}
}
and here the derived class (Undergrad)
public class Undergrad extends Student {
private String year;
public Undergrad (int id , String name ,double gpa,String year)
{
super(id,name , gpa);
this.year =year;
}
@Override
public String toString(){
return super() + " the year is :" + year;
}
}
the problem i'm facing is that eclipse shows that I have
a mistake in toString method in class Undergrad
exactly at the super() invoke the error says
"Syntax error on token "super", invalid Name"
could I find any help please ?
Answer
super()
call is allowed only in constructors.
you need to call super.toString()
if you want to call super class method.
public String toString()
{
return super.toString() + " the year is :" + year;
}
This is the syntax for super
keyword
1.for calling a superclass constructor is
- super(); //the superclass no-argument constructor is called
- super(parameter list);//the superclass constructor with a matching parameter list is called
2.for calling a superclass member is
- super.fieldName;//here member is field of super class
- super.methodName();//here member is method of super class
No comments:
Post a Comment