What does the super keyword represents and where can it be used? Give an example
ID: 3782719 • Letter: W
Question
What does the super keyword represents and where can it be used? Give an example of a superclass and subclass. Be sure to make all the instances variables of the super class private. Include at least one constructor in each class and ensure that the constructor of the subclass calls the constructor of the superclass. Also include a toString method in both classes that returns the values of the instance variables with appropriate labels. Ensure that the toString method of subclass calls the toString method of the superclass so that the string returned contains the values of all the inherited instance variables.
Explanation / Answer
Solution:
/**Super keyword is used to invoke the superclass constructor or method of super class into subclass.
Lets take an example of superclass and sub class: **/
public class Printjob {
private String userName;
private int userPriority;
private int noOfPages;
/***
*
* @param name
* @param p
* @param pages
*/
Printjob(String name, int p, int pages) {
this.userName = name;
this.userPriority = p;
this.noOfPages = pages;
}
/**
* @return the userName
*/
public String getUserName() {
return userName;
}
/**
* @param userName
* the userName to set
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* @return the userPriority
*/
public int getUserPriority() {
return userPriority;
}
/**
* @param userPriority
* the userPriority to set
*/
public void setUserPriority(int userPriority) {
this.userPriority = userPriority;
}
/**
* @return the noOfPages
*/
public int getNoOfPages() {
return noOfPages;
}
/**
* @param noOfPages
* the noOfPages to set
*/
public void setNoOfPages(int noOfPages) {
this.noOfPages = noOfPages;
}
@Override
public String toString() {
return "Printjob [userName=" + userName + ", userPriority="
+ userPriority + ", noOfPages=" + noOfPages + "]";
}
}
public class OutsidePrintjob extends Printjob {
private double cost;
/**
*
* @param name
* @param p
* @param pages
*/
public OutsidePrintjob(String name, int p, int pages) {
super(name, p, pages);
cost = (super.getNoOfPages() * super.getUserPriority()) * 10;
}
/**
* @return the cost
*/
public double getCost() {
return cost;
}
/**
* @param cost
* the cost to set
*/
public void setCost(double cost) {
this.cost = cost;
}
@Override
public String toString() {
return super.toString() + " " + "OutsidePrintjob [cost=" + cost + "]";
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.