[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Inheritance in Java - Clarification

Posted on 2009-04-26
5
Medium Priority
?
2,733 Views
Last Modified: 2013-11-23
This assignment has a few classes, and I am confused if I am doing everything correctly.
The program compiles and runs just fine.  I am just looking for some comments/suggestions that may make this better.  
package courseGrades;
 
public class CourseGrades extends GradedActivity{
	
	static GradedActivity []grades = new GradedActivity[5];
	
	public static void setLab(GradedActivity obj){
		
		grades[0] = obj;
	}
	
	public static void setPassFailExam(GradedActivity Object){
		grades[1] = Object;
	}
	
	public static void setEssay(GradedActivity c){
		grades[2] = c;
	}
	public static void setFinalExam(FinalExam Object){
		grades[3] = Object;
	}
	public static void setTotalGrade(GradedActivity Object){
		grades[4] = Object;
	}
	public String toString(){
		return grades.toString();
	}
}
 
package courseGrades;
 
/**
 * Essay class Chapter 9, Programming Challenge 4
 */
 
public class Essay extends GradedActivity {
	private double grammar; // Points for grammar
	private double spelling; // Points for spelling
	private double correctLength; // Points for length
	private double content; // Points for content
 
	/**
	 * setScore method Overloads the base class method. Note that the other
	 * "set" methods are private. Those methods are for validating points before
	 * they are assigned.
	 */
 
	public void setScore(double gr, double sp, double len, double cnt) {
		// Set the individual scores.
		setGrammar(gr);
		setSpelling(sp);
		setCorrectLength(len);
		setContent(cnt);
 
		// Set the total score.
		super.setScore(grammar + spelling + correctLength + content);
	}
 
	/**
	 * setGrammar method This method validates that the grammar points before
	 * they are set.
	 */
 
	private void setGrammar(double g) {
		if (g <= 30.0)
			grammar = g;
		else
			// Invalid points
			grammar = 0.0;
	}
 
	/**
	 * setSpelling method This method validates that the spelling points before
	 * they are set.
	 */
 
	private void setSpelling(double s) {
		if (s <= 20.0)
			spelling = s;
		else
			// Invalid points
			spelling = 0.0;
	}
 
	/**
	 * setCorrectLength method This method validates that the length points
	 * before they are set.
	 */
 
	private void setCorrectLength(double c) {
		if (c <= 20.0)
			correctLength = c;
		else
			// Invalid points
			correctLength = 0.0;
	}
 
	/**
	 * setContent method This method validates that the content points before
	 * they are set.
	 */
 
	private void setContent(double c) {
		if (c <= 30)
			content = c;
		else
			// Invalid points
			content = 0.0;
	}
 
	/**
	 * getGrammar method
	 */
 
	public double getGrammar() {
		return grammar;
	}
 
	/**
	 * getSpelling method
	 */
 
	public double getSpelling() {
		return spelling;
	}
 
	/**
	 * getCorrectLength method
	 */
 
	public double getCorrectLength() {
		return correctLength;
	}
 
	/**
	 * getContent method
	 */
 
	public double getContent() {
		return content;
	}
 
	/**
	 * The getScore method returns the overall numeric score. Overrides the base
	 * class method.
	 */
 
	public double getScore() {
		return grammar + spelling + correctLength + content;
	}
}
 
package courseGrades;
 
/**
 * This class determines the grade for a final exam.
 */
 
public class FinalExam extends GradedActivity {
	private int numQuestions; // Number of questions
	private double pointsEach; // Points for each question
	private int numMissed; // Number of questions missed
 
	/**
	 * The constructor accepts as arguments the number of questions on the exam
	 * and the number of questions the student missed.
	 */
 
	public FinalExam(int questions, int missed) {
		double numericScore; // To calculate the numeric score
 
		// Set the numQuestions and numMissed fields.
		numQuestions = questions;
		numMissed = missed;
 
		// Calculate the points for each question and
		// the numeric score for this exam.
		pointsEach = 100.0 / questions;
		numericScore = 100.0 - (missed * pointsEach);
 
		// Call the superclass's setScore method to
		// set the numeric score.
		setScore(numericScore);
	}
 
	/**
	 * The getPointsEach method returns the pointsEach field.
	 */
 
	public double getPointsEach() {
		return pointsEach;
	}
 
	/**
	 * The getNumMissed method returns the numMissed field.
	 */
 
	public int getNumMissed() {
		return numMissed;
	}
	
	/**
	 * The getNumQuestions method returns the NumQuestions field.
	 */
	
	public int getNumQuestions() {
		return numQuestions;
	}
}
 
package courseGrades;
 
/**
 * A class that holds a grade for a graded activity.
 */
 
public class GradedActivity {
	private double score; // Numeric score
 
	/**
	 * The setScore method stores its argument in the score field.
	 */
 
	public void setScore(double s) {
		score = s;
	}
 
	/**
	 * The getScore method returns the score field.
	 */
 
	public double getScore() {
		return score;
	}
 
	/**
	 * The getGrade method returns a letter grade determined from the score
	 * field.
	 */
 
	public char getGrade() {
		char letterGrade; // To hold the grade
 
		if (score >= 90)
			letterGrade = 'A';
		else if (score >= 80)
			letterGrade = 'B';
		else if (score >= 70)
			letterGrade = 'C';
		else if (score >= 60)
			letterGrade = 'D';
		else
			letterGrade = 'F';
 
		return letterGrade;
	}
}
 
package courseGrades;
 
/**
 * This class holds a numeric score and determines whether the score is passing
 * or failing.
 */
 
public class PassFailActivity extends GradedActivity {
	private double minPassingScore; // Minimum passing score
	private int numQuestions;	// Number of Questions on activity
 
	/**
	 * The constructor accepts the minimum passing score as its argument.
	 */
 
	public PassFailActivity(int questions, double mps) {
		
		minPassingScore = mps;
		numQuestions = questions;
	}
 
	/**
	 * The getGrade method returns a letter grade determined from the score
	 * field. This method overrides the superclass method.
	 */
 
	public char getGrade() {
		char letterGrade; // To hold the letter grade
 
		if (super.getScore() >= minPassingScore)
			letterGrade = 'P';
		else
			letterGrade = 'F';
 
		return letterGrade;
	}
	public int getNumQuestions() {
		return numQuestions;
	}
 
}
 
package courseGrades;
 
/**
 * This class determines a passing or failing grade for an exam.
 */
 
public class PassFailExam extends PassFailActivity {
	private int numQuestions; // Number of questions
	private double pointsEach; // Points for each question
	private int numMissed; // Number of questions missed
 
	/**
	 * The constructor accepts as arguments the number of questions on the exam,
	 * the number of questions the student missed, and the minimum passing
	 * score.
	 */
 
	public PassFailExam(int questions, int missed, double minPassing) {
		// Call the superclass constructor.
		super(questions, minPassing);
 
		// Declare a local variable for the numeric score.
		double numericScore;
 
		// Set the numQuestions and numMissed fields.
		numQuestions = questions;
		numMissed = missed;
 
		// Calculate the points for each question and
		// the numeric score for this exam.
		pointsEach = 100.0 / questions;
		numericScore = 100.0 - (missed * pointsEach);
 
		// Call the superclass's setScore method to
		// set the numeric score.
		setScore(numericScore);
	}
 
	/**
	 * The getPointsEach method returns the pointsEach field.
	 */
 
	public double getPointsEach() {
		return pointsEach;
	}
 
	/**
	 * The getNumMissed method returns the numMissed field.
	 */
 
	public int getNumMissed() {
		return numMissed;
	}
	
	/**
	 * The getNumQuestions method returns the NumQuestions field.
	 */
	
	public int getNumQuestions() {
		return numQuestions;
	}
}
 
package courseGrades;
 
public class CourseGradesDemo {
 
	public static void main(String[] args){
		
		// Create objects.
		GradedActivity labActivity = new GradedActivity();
		GradedActivity totalGrade = new GradedActivity();
	    Essay termPaper = new Essay();
	    PassFailActivity passFailExam = new PassFailActivity(10,70);
	    FinalExam finalTest = new FinalExam(50, 4);
	      
	    // Assign scores to the object.
	    // Grammer = 25 points, Spelling = 18 points,
	    // Length = 20 points, and Content = 25 points.
	    termPaper.setScore(25.0, 18.0, 20.0, 25.0);
	    labActivity.setScore(89);
	    passFailExam.setScore(95);
	    	    
	    CourseGrades.setLab(labActivity);
	    CourseGrades.setEssay(termPaper);
	    CourseGrades.setPassFailExam(passFailExam);
	    CourseGrades.setFinalExam(finalTest);
	    	    	    
	    double LabScore = CourseGrades.grades[0].getScore();
	    char LabGrade = CourseGrades.grades[0].getGrade();
	    double ExamScore = CourseGrades.grades[1].getScore();
	    char ExamGrade = CourseGrades.grades[1].getGrade();
	    double PaperScore = CourseGrades.grades[2].getScore();
	    char PaperGrade = CourseGrades.grades[2].getGrade();
	    double FinalScore = CourseGrades.grades[3].getScore();
	    double FinalNumMissed = ((FinalExam) CourseGrades.grades[3]).getNumMissed();
	    char FinalGrade = CourseGrades.grades[3].getGrade();
	    
	    // Display the score details.
	    System.out.println("Lab Activity: ");
	    System.out.println("\tScore: " + LabScore);
	    System.out.println("\tGrade: " + LabGrade);
	      
	    System.out.println("\nPass/Fail Exam:");
	    System.out.println("\tScore: " + ExamScore);
	    System.out.println("\tGrade: " + ExamGrade);
	    
	    System.out.println("\nTerm paper:");
	    //System.out.println("Grammar points: " + termPaper.getGrammar());
	    //System.out.println("Spelling points: " + termPaper.getSpelling());
	    //System.out.println("Length points: " + termPaper.getCorrectLength());
	    //System.out.println("Content points: " + termPaper.getContent());
	    System.out.println("\tScore: " + PaperScore);
	    System.out.println("\tGrade: " + PaperGrade);
	     
	    System.out.println("\nFinal Exam:");
	    System.out.println("\tScore: " + FinalScore);
	    System.out.println("\tMissed questions: " + FinalNumMissed);
	    System.out.println("\tGrade: " + FinalGrade);	
	    
	    double TotalScore = ((LabScore + ExamScore + PaperScore + FinalScore)/4);
	    
	    totalGrade.setScore(TotalScore);
	    CourseGrades.setTotalGrade(totalGrade);
	    
	    char TotalGrade = CourseGrades.grades[4].getGrade();
	    
	    System.out.println("\nFinal Score: " + TotalScore);
	    System.out.println("\nFinal Grade: " + TotalGrade);
	}
}

Open in new window

0
Comment
Question by:b_acs
  • 2
  • 2
5 Comments
 

Accepted Solution

by:
urlgrrrl earned 750 total points
ID: 24238928
Here are a few suggestions for improving your project:
  1. Does GradedActivity need to be a base class?
    You have classes such as FinalExam inherit from GradedActivity as a way of indicating that those are types of GradedActivity.  An alternative is to define GradedActivity as an interface that the other classes implement.  That will give you more flexibility in your design because objects that inherit from other base classes could then implement GradedActivity.  Remember that Java lets a class inherit from one and only one superclass, so you want to use it sparingly.  On the other hand, classes may implement multiple interfaces.
  2. Does method GradedActivity.getScore( )  belong in GradedActivity?
    This method takes the activity's number score and converts it to a letter grade.  Methods that convert or format a single value like this are often more useful as static methods that take a value as an input parameter.  That allows the method to be used more like a function and not require you to instantiate a class in order to use it.  Once that method is removed, GradedActivity could be changed to an interface.  Of course, getScore( ) has to be moved somewhere else.  
  3. Is CourseGrades a type of GradedActivity?
    This class contains a collection of GradedActivity objects, but does not represent a student activity itself.  So it should not inherit from GradedActivity.   This class would also be a good place to move the getScore( ) from GradedActivity.  The method would be useful, for example, if you chose to format the grades in the toString( ) method with letter grades.
I hope you find these suggestions helpful.
0
 

Author Comment

by:b_acs
ID: 24239111
OK I do believe that GradedActivity is supposed to be a base class for this, since I was given the code for the classes that inherit from it.  

As for the getScore() method I couldn't figure out how to move it out of GradedActivity without making a ton of changes.  Also, even then I couldn't get to compile without adding the method to each class.

I didn't catch that the CourseGrades class wasn't inheriting from GradedActivity, so Thank You for that one!
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24239611
Generally speaking, GradedActivity should be a subclass of Activity
0
 

Author Comment

by:b_acs
ID: 24247032
Thank You CEHJ
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24248308
No problem
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:
Suggested Courses
Course of the Month19 days, 18 hours left to enroll

872 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question