I am trying to complete the Appendix attached Appendix. I just want to know if I am coding it correctly according to the Appendix and that I am using the correct approach. I am not sure if I did the correct thing under interest(). Where I called the super classes is that correct?
public interface LoanInterest {
double interest();
String getName();
String toString();
} //end of LoanInterest
public abstract class Student implements LoanInterest {
private String name;
private String studentNumber;
private double feesOwed;
public Student(String nm, String num, double amt) {
name = nm;
studentNumber = num;
feesOwed = amt;
}
public double getFeesOwed() {
return feesOwed;
}
public String getStudentNumber() {
return studentNumber;
}
public String getName() {
return name;
}
public String toString() {
String msg;
msg = String.format("%s\t%s\t%.2f", name, getStudentNumber(), getFeesOwed());
return msg;
}
} //end of Student
public class UnderGrad extends Student {
public UnderGrad(String nm, String num, double amt) {
super(nm, num, amt);
}
public double interest() {
return super.getFeesOwed() + (super.getFeesOwed() * 0.14);
}
} //end of UnderGrad
public class PostGrad extends Student {
private String diploma;
public PostGrad(String nm, String num, double amt) {
super(nm, num, amt);
}
public String getDiploma() {
return diploma;
}
public double interest() {
return super.getFeesOwed() + (super.getFeesOwed() * 0.14);
}
} //end of PostGrad
You don't need to call super.methodName, since you do not override them in PostGrad or UnderGrad, but it is not "wrong" either.
So you can write:
public double interest() {
return getFeesOwed() + (getFeesOwed() * 0.14);
}
And if you would override them, you most likely want to use them too, so again no super.
The super keyword is normally used, if a method is overridden to add some additional functionality to it, without completely rewriting the code of the overridden method.
Related
I was going through adapter design pattern, and found we can allow us to collaborate with incompatible interface.
Now suppose, I found this example on stackoverflow.
public interface IWetherFinder {
public double getTemperature(String cityName);
}
class WeatherFinder implements IWetherFinder{
#Override
public double getTemperature(String cityName){
return 40;
}
}
interface IWeatherFinderClient
{
public double getTemperature(String zipcode);
}
public class WeatherAdapter implements IWeatherFinderClient {
#Override
public double getTemperature(String zipcode) {
//method to get cityname by zipcode
String cityName = getCityName(zipcode);
//invoke actual service
IWetherFinder wetherFinder = new WeatherFinder();
return wetherFinder.getTemperature(cityName);
}
private String getCityName(String zipCode) {
return "Banaglore";
}
}
Now in this case can't we add one more method to existing interface something Like below.
public interface IWetherFinder {
public double getTemperature(String cityName);
public double getTemperatureByZipcode(String zipCode);
}
class WeatherFinder implements IWetherFinder{
#Override
public double getTemperature(String cityName){
// some logic to get temp by city
return 40;
}
#Override
public double getTemperatureByZipcode(String zipCode){
String city = getCityName(zipCode);
//some logic to get the temp by city name
return 40;
}
private String getCityName(String zipCode) {
return "Banaglore";
}
}
Is it possible to protect from performing code placed in superclass constructor? In this example the output is
From Person
From Student
but I don't need to print out From Person. If I delete super(a, n); then program will not compile. Is it possible to print out only message from subclass?
class Person {
private int age;
private String name;
public Person(int a, String n) {
this.age = a;
this.name = n;
System.out.println("From Person");
}
public int getAge() {
return age;
}
public void setAge(int a) {
this.age = a;
}
public String getName() {
return name;
}
public void setName(String n) {
this.name = n;
}
}
class Student extends Person {
private String specialization;
public Student(int a, String n, String s) {
super(a, n);
specialization = s;
System.out.println("From Student");
}
public String getSpecialization() {
return specialization;
}
public void setSpecialization(String s) {
this.specialization = s;
}
}
public class Classes {
public static void main(String[] args) {
Student student_Jack = new Student(20, "Jack", "IT");
}
}
Instead of using super(a,n) you should use your methods for setting those variables that you have made.
public Student(int a, String n, String s) {
setAge(a);
setName(n);
specialization = s;
System.out.println("From Student");
}
You must also add an empty constructor in person.
public Person(){}
This will give you the same functionality, without needing to call the super constructor.
I'm working on a task which has the following classes:
Vehicle.java ( Abstract Class)
NewVehicle.java subClass of Vehicle.java
UsedVehicle.java subClass of Vehicle.java
VehicleParser.java used as a parser
Drive Class which is used as main
In the VehicleParser class I determine which object it is. Either it is a NewVehicle object or a UsedVehicle. And in the Drive class I fill an ArrayList with the Vehicle objects.
Now When I'm trying to System.out.println an Arraylist the drive class is just invoking toString method declared in UsedVehicle/NewVehicle but not invoking the method declared in the Vehicle.java class. I need it to first invoke the method toString of Vehicle and then concat the toString of UsedVehicle/NewVehicle with it.
Here is the Code:
Vehicle
public abstract class Vehicle {
protected String make;
protected int modelYear;
protected String motivePower;
protected double licenseFee;
public Vehicle(String make,int modeYear,String motivePower) {
this.make = make;
this.modelYear= modeYear;
this.motivePower = motivePower;
this.licenseFee = 0.0;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public int getModelYear() {
return modelYear;
}
public void setModelYear(int modelYear) {
this.modelYear = modelYear;
}
public String getMotivePower() {
return motivePower;
}
public void setMotivePower(String motivePower) {
this.motivePower = motivePower;
}
public double getLicenseFee() {
return licenseFee;
}
public void setLicenseFee(double licenseFee) {
this.licenseFee = licenseFee;
}
public abstract void computeLicenseFee();
public String toString()
{
return "\nMake:\t\t"+getMake()+
"\nModel Year:\t"+getModelYear()+
"\n Motive Power:\t"+getMotivePower()+
"\nLicense Fee:\t"+getLicenseFee();
}
public static class UsedVehicle extends Vehicle
{
public String previousLicenseState;
public int currentYear;
int yearsOld = 0;
public UsedVehicle(String make, int modelYear, String power, String previousState, int currentYear)
{
super(make,modelYear,power);
this.previousLicenseState = previousState;
this.currentYear = currentYear;
}
public String getPreviousLicenseState() {
return previousLicenseState;
}
public void setPreviousLicenseState(String previousLicenseState) {
this.previousLicenseState = previousLicenseState;
}
public int getCurrentYear() {
return currentYear;
}
public void setCurrentYear(int currentYear) {
this.currentYear = currentYear;
}
public void computeLicenseFee() {
double baseFee = 100.00;
double titleTransferFee = 15.00;
double smogWaiverFee = 0.00;
double smogAbatement = 0.00;
yearsOld = getCurrentYear() - getModelYear();
if(yearsOld > 5)
{
smogWaiverFee = 8.00;
}
if("gas".equalsIgnoreCase(getMotivePower()))
{
smogAbatement = 20.00;
}
licenseFee = baseFee + smogAbatement + titleTransferFee + smogWaiverFee;
}
public String toString()
{
return "\n Years Old:\t"+yearsOld+
"\n Previous State:\t"+getPreviousLicenseState();
}
}
public static class NewVehicle extends Vehicle
{
public double vehiclePrice;
public NewVehicle(String make, int modeYear, String motivePower,double price) {
super(make, modeYear, motivePower);
this.vehiclePrice = price;
}
public double getVehiclePrice() {
return vehiclePrice;
}
public void setVehiclePrice(double vehiclePrice) {
this.vehiclePrice = vehiclePrice;
}
public void computeLicenseFee() {
double baseFee = 150.00;
double smogAbatement = 0.00;
double priceFee = 0.00;
if("gas".equalsIgnoreCase(getMotivePower()))
{
smogAbatement = 20.0;
priceFee = getVehiclePrice()*0.15;
}
licenseFee = baseFee + smogAbatement + priceFee;
}
public String toString()
{
return "Price:\t\t$"+getVehiclePrice();
}
}
}
Parser
public class VehicleParser {
public static Vehicle parseStringToVehicle(String lineToParse)
{
Vehicle vehicleObj = null;
Vehicle.UsedVehicle usedVeh = new Vehicle.UsedVehicle(make, modelYear, power, previousState, currentYear);
return vehicleObj;
}
}
DriveClass
Vehicle obj = VehicleParser.parseStringToVehicle(inputInfo);
vehicleList.add(obj);
System.out.println(vehicleList.get(i));
You are overriding the toString() method. Java doesn't do any special magic here. If you want the super class' method to be called, you need to do so explicitly with the super keyword:
#Override
public String toString()
{
return super.toString() + // Here
"\n Years Old:\t"+yearsOld+
"\n Previous State:\t"+getPreviousLicenseState();
}
Just consider this example:
public class A {
public String someMethod() {
return "A method";
}
}
public class B extends A {
#Override
public String someMethod() {
return "B method";
}
}
public class C extends B {
#Override
public String someMethod() {
return "C method";
}
}
Basically what's going on here is that when you inherit the parent class, you're overriding everything that's in parent class's method and you're giving new definition to it. By Overriding parent class's method, you're saying that:
I'm giving a new fresh definition to this method. From now onward, for all of my objects and my child's object, this is only going to be the definition that would be considered and any of parent's method definition is void.
Now if you want the parent's method definition to be called before calling this method definition, then you'd have to specifically state that using super.methodName() in your code.
public class A {
public String someMethod() {
return "A method";
}
}
public class B extends A {
#Override
public String someMethod() {
return super.someMethod() + "B method";
}
}
public class C extends B {
#Override
public String someMethod() {
return super.someMethod() + "C method";
}
}
When you call the subclass methods the overridden methods will be called and all the definitions in the parent's method will be overridden and you will get only the overridden method definition. So inprder to use the parents' method definition as well you need to use the super() method in your child class method...
return super.toString() + " is a new car!";
This is a java code with inheritance and polymorphism methods.
Student Class
public abstract class Student
{
protected long id;
protected String name;
protected String programCode;
protected int part;
public Student(){
id=0;
name=" ";
programCode=" ";
part=0;
}
public void setStudent(long i,String nm,String code,int pt){
id=i;
name=nm;
programCode=code;
part=pt;
}
public long getId() {return id;}
public String getName() {return name;}
public String getProgramCode() {return programCode;}
public int getPart() {return part;}
public abstract double calculateFees();
public String toString(){
return ("ID: "+id+"\nName: "+name+"\nProgram Code: "+programCode+"\nPart: "+part);}
}
FullTimeStudent Class
public class FullTimeStudent extends Student{
protected String collegeName;
protected String roomNumber;
public FullTimeStudent(){
super();
collegeName=" ";
roomNumber=" ";
}
public FullTimeStudent(long i,String nm,String code,int pt,
String collegeNm,String roomNum){
super(i,nm,code,pt); //can't find symbol here
collegeName=collegeNm;
roomNumber=roomNum;
}
public void setFullTimeStudent(String collegeNm,String roomNum){
collegeName=collegeNm;
roomNumber=roomNum;
}
public String getCollegeName() {return collegeName;}
public String getRoomNumber() {return roomNumber;}
public double calculateFees(){
double fee=0, collegefee=0, totalfee=0;
if(programCode.equals("BIT")){
fee=2000;
}
else if(programCode.equals("BCHE")){
fee=2300;
}
else if(programCode.equals("BPHY")){
fee=3200;
}
else if(programCode.equals("BBIO"))
fee=2700;
}
if(collegeName.equals("Jati")){
collegefee=200;
}
else if(collegeName.equals("Cengal")){
collegefee=350;
}
else if(collegeName.equals("Dahlis")){
collegefee=420;
totalfee=fee+collegefee;
return totalfee;
}
public String toString(){
return super.toString()+"\nCollege Name: "+collegeName+"\nRoom Number"+roomNumber;
}
}
It seems that it can't find the symbol of the super statement in the FullTimeStudent
class.
super(i,nm,code,pt);
As the error is trying to tell you, your superclass does not have any constructor that takes parameters.
Change the method declaration of Student#setStudent to that of an overloaded constructor expected in the constructor of FullTimeStudent
protected Student(long i, String nm, String code, int pt) {
id = i;
name = nm;
programCode = code;
part = pt;
}
The no-args constructor can then be simplified to
protected Student() {
this(0, " ", " ", 0);
}
(will leave the translation of literal values to predefined constants as an exercise)
I finished all the classes except for the student class. I don't understand how to approach it. Here is the prompt.
Extend the Person class developed in
lab1 to derive classes for students,
hourly employees, and full-time
salaried employees. Determine an
appropriate class inheritance
hierarchy. These classes should have
the following fields, necessary
constructors, and appropriate access
and modifier methods.
for all employees:
*department
full-time employees:
*salary
hourly employees:
*hourly rate
*number of hours worked each week(4weeks)
the hourly employee class should
contain the necessary methods that
will print the total hours (four- week
total), average hours per week worked
by each employee, and the total wages
during a four-week period.
student:
*classes taken and grades for each class (use an ArrayList)
The student class should contain the
necessary methods to print the
transcript for each student
(write a tester class to test your
classes)
How should I use an arraylist for the student class?
I'm only going to post the relevant classes
public class Person { private String first; private String last; private static int idNumber = 1001; int Id ; private String full;
Person(){
}
Person(String fn,String ln){
first = fn;
last = ln;
Id = idNumber++;
full = first +" "+ last;
}
static int getidNumber(){
return idNumber;
}
void setfirst(String fn) {
first = fn;
}
String getfirst(){
return first; }
void setlast(String ln){
last = ln; }
String getlast(){
return last; }
#Override
public String toString(){
String blah = "First name: " +first+ " Last Name:" +last+ "\tThe full name is: "+full+" Id#"+Id;
return blah;
}
}
import java.util.*;
public class Student extends Person{
Student (String fn, String ln){
super(fn,ln);
}
}
Thank you in advance for all advices and suggestions.
I would use a map here, but since an ArrayList is required, I would do something like that:
public class Student extends Person {
private List<ClassGrade> classes = new ArrayList<ClassGrade>();
public List<ClassGrade> getClassGrades() {
return new ArrayList<ClassGrade>(classes);
}
public void addClass(String clazz, int grade) {
classes.add(new ClassGrade(clazz, grade));
}
public static class ClassGrade {
String clazz;
int grade;
public ClassGrade(String clazz, int grade) {
this.clazz = clazz;
this.grade = grade;
}
public String getClazz() {
return clazz;
}
public int getGrade() {
return grade;
}
}
}
import static java.lang.System.*;
class Student extends Person
{
protected int avMark;
String classTaken
public Student()
{
}
public Student(String nameInput, int ageInput, String class)
{
super(nameInput, ageInput);
classTaken = class;
}
public void setClasTaken(String className){
classTaken = classname;
}
public String setClasTaken(){
return classTaken;
}
public void register()
{
super.register();
out.println("Classes taken " +classTaken
out.println("Average mark is " + avMark);
}
}
here is something to start you off
this class inherits everything from the person class.