In: Computer Science
Consider the following class definition:
public class Parent {
private int varA;
protected double varB;
public Parent(int a, double b){
varA = a;
varB = b;
}
public int sum( ){
return varA + varB;
}
public String toString( ){
return "" + varA + " " + varB;
}
}
Consider that you want to extend Parent to Child. Child will have a third int instance data varC.
Using the class definitions for Parent and Child from Question 2, write a Java application that will represent a family of 4 members.
Child.java
public class Child extends Parent {
private int varC;
public Child(int a, double b, int c) { //
parameretized construc
super(a, b);
varC = c;
}
@Override
public int sum() { // overridden sum
return super.sum() + varC; //
returns sum of all three variables
}
public double average() { // average method
return (varB + varC) / 2; //
returns average
}
@Override
public String toString() { // overridden
toString
return super.toString() + " " +
varC;
}
}
Application.java
import java.util.Scanner;
public class Application { // Application
public static void main(String[] args) {
Scanner input = new
Scanner(System.in);
Parent p1 =
getParentfromUser(input, 1);
Parent p2 =
getParentfromUser(input, 2);
Child c1 = getChildfromUser(input,
1);
Child c2 = getChildfromUser(input,
2);
Parent[] family = {p1, p2, c1,
c2};
System.out.println("average of
child " + 1 + " " + c1.average());
System.out.println("average of
child " + 2 + " " + c2.average());
for(Parent p : family) {
System.out.println(p);
}
}
static Parent getParentfromUser(Scanner input, int
id) {
Parent parent;
System.out.println("input varA for
parent " + id);
int a = input.nextInt();
System.out.println("input varB for
parent " + id);
double b =
input.nextDouble();
parent = new Parent(a, b);
return parent;
}
static Child getChildfromUser(Scanner input, int
id) {
Child child;
System.out.println("input varA for
child " + id);
int a = input.nextInt();
System.out.println("input varB for
child " + id);
double b =
input.nextDouble();
System.out.println("input varC for
child " + id);
int c = input.nextInt();
child = new Child(a, b, c);
return child;
}
}
Output:
input varA for parent 1
1
input varB for parent 1
2
input varA for parent 2
3
input varB for parent 2
4
input varA for child 1
2
input varB for child 1
1
input varC for child 1
3
input varA for child 2
5
input varB for child 2
5
input varC for child 2
5
average of child 1 2.0
average of child 2 5.0
1 2.0
3 4.0
2 1.0 3
5 5.0 5