I am fairly new to Inheritance, and I'm not sure if I am doing it right but I seem to be on the right track. The program runs fine except the output I am getting isn't right. I think the problem is to do with my constructors.
public class Person {
protected static String name;
protected static int birthYear;
public Person(String name, int birthYear) {
}
public String name (String n) {
n = name;
return n;
}
public int birthYear (int bY) {
bY = birthYear;
return bY;
}
#Override
public String toString() {
return String.format(name + birthYear);
}
}
public class Student extends Person {
protected String major;
public Student(String name, int birthYear, String major) {
super(name, birthYear);
major = "";
}
public String major(String maj) {
maj = major;
return maj;
}
public String toString() {
super.toString();
return super.toString() + major;
}
}
public class Instructor extends Person {
protected static int salary;
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
salary = 0;
}
public int salary(int sal) {
sal = salary;
return sal;
}
public String toString() {
super.toString();
return super.toString() + salary;
}
}
public class PersonTester {
public static void main(String[] args) {
Person p = new Person("Perry", 1959);
Student s = new Student("Sylvia", 1979, "Computer Science");
Instructor e = new Instructor("Edgar", 1969, 65000);
System.out.println(p);
System.out.println("Expected: Person[name=Perry,birthYear=1959]");
System.out.println(s);
System.out.println("Expected:" +
"Student[super=Person[name=Sylvia,birthYear=1979],major=Computer]");
System.out.println(e);
System.out.println("Expected:" + "Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]");
}
}
OUTPUT I AM GETTING:
null0
Expected: Person[name=Perry,birthYear=1959]
null0null
Expected: Student[super=Person[name=Sylvia,birthYear=1979],major=Computer Science]
null00
Expected: Instructor[super=Person[name=Edgar,birthYear=1969],salary=65000.0]
Try changing your constructor in Person to:
public Person(String name, int birthYear) {
this.name = name;
this.birthYear = birthYear;
}
Currently, the constructor has an empty body, so when you call super(name, birthYear); in the subclass constructor, nothing actually happens.
Your Student constructor also has an error. You forgot to initialize the major field.
public Student(String name, int birthYear, String major) {
super(name, birthYear);
this.major = major;
}
You have the same problem in the Instructor constructor...
public Instructor(String name, int birthYear, int salary) {
super(name, birthYear);
this.salary = salary;
}
Finally, you need to take away the static keywords before the fields in Person. This is because static ensures, that there will always be one (and only one) instance of those fields per class, as opposed to one per instance, like you want it to be:
protected String name;
protected int birthYear;
Same thing for the salary field in Instructor.
n = name; this causing your problem. It must be name = n;. All your setter function contain this problem, correct them all and tell me result.
Related
I am working on a java code to create a class Students and I should define two constructors and one has to be with parameters and one without parameters I have already done the one with parameters but I am having a problem understanding how to do the one without parameters This is what I have to do:
setStudent()that takes three parameters: a string name, an integer grade, and a double cgpa value.
It stores these parameters into the three member variables of the class.
getNamethat returns the value stored in the member variable name.
getGradethat returns the value stored in the member variable grade.
getCGPAthat returns the value stored in the member variable cgpa.
printStudent that displays the values of the three member variables.
I have done most but I do not know what to do with the last thing printStudent.
My class :
public class Students{
private String Name;
private int Grade;
private double CGPA;
public Students(String Name, int Grade, double CGPA){
this.Name = Name;
this.Grade = Grade;
this.CGPA = CGPA;
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public int getGrade(){
return Grade;
}
public void setGrade(int Grade){
this.Grade = Grade;
}
public double getCGPA(){
return CGPA;
}
public void setCGPA(double CGPA){
this.CGPA = CGPA;
}
}
and that is my main :
public class LAB4EX1{
public static void main(String [] args){
Students student1 = new Students("Nasser", 90, 3.4);
Students student2 = new Students("Adnan", 92, 3.72);
Students student3 = new Students("Mohammed", 91, 3.5);
}
}
I need to make it print the output for me.
Any help would be really appreciated.
You have do declare a constructor without any parameters and override toString method:
public class Students{
private String Name;
private int Grade;
private double CGPA;
public Students(String Name, int Grade, double CGPA){
this.Name = Name;
this.Grade = Grade;
this.CGPA = CGPA;
}
public Students(){ // empty constructor
}
public String getName(){
return Name;
}
public void setName(String Name){
this.Name = Name;
}
public int getGrade(){
return Grade;
}
public void setGrade(int Grade){
this.Grade = Grade;
}
public double getCGPA(){
return CGPA;
}
public void setCGPA(double CGPA){
this.CGPA = CGPA;
}
#Override
public String toString() {
return "Students{" +
"Name='" + Name + '\'' +
", Grade=" + Grade +
", CGPA=" + CGPA +
'}';
} // toString() for printing your three fields
}
My professor gave us this homework exercise and has created a project with
a bunch of unit tests.
Our goal is to make sure we can pass those unit tests.
We have three classes.
A class called Person with a name and an age,
a class Speaker that extends Person,
and a class Attendee that also extends Person.
I am struggling with making sure that there are no duplicate people. generateRandomString() was implemented by the professor and just returns a random string.
I already created the class,
it's constructor,
getters,
and setters.
I also overrode the method equals() in the class Person
This is the test our professor gave us:
#Test
public void testNoDuplicatePerson() {
HashSet<Person> people = new HashSet<Person>();
String name = generateRandomString();
Person p = new Speaker(name);
people.add(p);
assertEquals(1,people.size());
p = new Attendee(name);
people.add(p);
assertEquals(1,people.size());
}
How can I pass this test?
EDIT: I decided to post the code of the three classes:
Person
```java
public abstract class Person {
private String name;
private int age;
public Person(String name) {
this.name = name;
this.age = 0;
}
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public boolean equals(Object o) {
if (o == null || !(o instanceof Person))
return false;
Person converted = (Person) o;
if (this.getName().equals(converted.getName()) && this.getAge() == converted.getAge())
return true;
return false;
}
}
Speaker:
public class Speaker extends Person {
private int fee;
public Speaker(String name) {
super(name);
this.fee = 0;
}
public Speaker(String name, int age) {
super(name, age);
this.fee = 0;
}
public Speaker(String name, int age, int fee) {
super(name, age);
this.fee = fee;
}
public int getFee() {
return fee;
}
public void setFee(int fee) {
this.fee = fee;
}
public String toString() {
return "Speaker " + this.getName() + " as a fee value of " + this.getFee() + ".";
}
}
Attendee:
public class Attendee extends Person {
private boolean paid;
public Attendee(String name) {
super(name);
this.paid=false;
}
public Attendee(String name, int age) {
super(name, age);
this.paid=false;
}
public boolean hasPaid(){
if (this.paid==true)
return true;
return false;
}
public String toString(){
return "Attendee "+this.getName()+(this.hasPaid() ? " has":" hasn't")+" paid its registration.";
}
}
As mentioned by #JB Nizet, when you override the equals method of a class,
you must override the hashCode method.
Note the name of the class in the jUnit test: HashSet.
That depends on the hashCode method.
Solution:
a. Learn to read the java API docs.
Here is a link to the v8 JavaDocs.
Read the HashSet page.
b. Implement the hashCode method.
You clearly have Internet access,
so, if you don't know how to implement a hashCode method,
try a google search for "how do I implement a Java hashCode method".
Hint: String already implements a hashCode method.
So as I understand, Goat class has no problem with a code,
I want to assign the first two elements from a new object, but I am not sure why it gives an runtime error
class Pet {
public String name;
public boolean indoor;
public Pet(String name, Boolean indoor) {
this.name = name;
this.indoor = indoor;
}
public String toString(){
return name + ", " + indoor;
}
}
class Goat extends Pet {
public int age;
public String diet;
public Goat(String name, boolean indoor, int age, String diet) {
super(name, indoor);
this.age = age;
this.diet = diet;
}
Here is the test code and error
}
The error is being thrown because, Pet class constructor is expecting Boolean and Goat class constructor is passing boolean. Although compiler is compiling code, but at runtime java is not able to find boolean type constructor. Hence, throwing no method error.
Correct Code will be
class Pet {
public String name;
public boolean indoor;
public Pet(String name, boolean indoor) {
this.name = name;
this.indoor = indoor;
}
public String toString(){
return name + ", " + indoor;
}
}
class Goat extends Pet {
public int age;
public String diet;
public Goat(String name, boolean indoor, int age, String diet) {
super(name, indoor);
this.age = age;
this.diet = diet;
}
I have 5 classes (they're small). PersonDemo (test class), Person (superclass), and Student, Instructor and Graduate Student (sub classes). All the classes except for PersonDemo are finished.
I need to read in a file (data.txt) and store it to array Person. Then need I need to determine which object to initialize depending on the first value of the array. ( 1 - person, 2 - student, 3 - instructor or 4 - graduate student ) - I'm having trouble with this part.
Can someone point me in the right direction? My classes are below along with what the input file (data.txt) looks like and what the output file should look like.
PersonDemo.Java
public class PersonDemo
{
public static void main ()
{
JFileChooser chooser = new JFileChooser();
Scanner fileScanner = null;
Person [] ins = new Person [10];
try {
if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION)
{
File selectedFile = chooser.getSelectedFile();
fileScanner = new Scanner(selectedFile);
while(fileScanner.hasNextLine())
{
// Need to load "data.txt" into array
// Then need I need to determine which object to initialize depending on the
// first value of the array in "data.txt"
//( 1 - person, 2 - student, 3 - instructor or 4 - graduate student )
}
fileScanner.close();
}
}
catch (FileNotFoundException e)
{
System.out.println("Could not find file");
}
}
public static void showAll(Person [] ins)
{
// Future code here
}
}
Person.java (superclass)
public class Person
{
private String name;
private int age;
public Person()
{
name="";
age=0;
}
public Person(String name, int age)
{
this.name = name;
this.age = age;
}
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
public String toString()
{
return "Name: " + name + "\t" + "Age: " + age;
}
}
Student.java (subclass)
public class Student extends Person
{
private int studentID;
private String major;
public Student()
{
studentID = 0;
major = "";
}
public Student(String name, int age, int studentID, String major)
{
super(name, age);
this.major = major;
this.studentID = studentID;
}
public int getID()
{
return studentID;
}
public void setID(int studentID)
{
this.studentID = studentID;
}
public String getMajor()
{
return major;
}
public void setMajor(String major)
{
this.major = major;
}
public String toString()
{
return super.toString() + "Student ID: " + studentID + "Major: " + major;
}
}
GraduateStudent.java (subclass)
public class GraduateStudent extends Student
{
private String researchArea;
public GraduateStudent()
{
researchArea = "";
}
public GraduateStudent(String name, int age, int studentID, String major, String researchArea)
{
super(name, age, studentID, major);
this.researchArea = researchArea;
}
public String getArea()
{
return researchArea;
}
public void setArea(String researchArea)
{
this.researchArea = researchArea;
}
public String toString()
{
return super.toString() + "Research Area: " + researchArea;
}
}
Instructor.java (subclass)
public class Instructor extends Person
{
private int salary;
public Instructor()
{
salary = 0;
}
public Instructor(String name, int age, int salary)
{
super(name, age);
this.salary = salary;
}
public int getSalary()
{
return salary;
}
public void setSalary(int salary)
{
this.salary = salary;
}
public String toString()
{
return super.toString() + "Salary: " + salary;
}
}
I have been struggling with setters and getters in java for quite a long time now.
For instance, if I want to write a class with some information as name, sex, age etc with appropriate set and get methods. Then in a another class I want to test my set and getters with this as a example:
personInfo = myInfo() = new Personinfo("Anna", "female", "17");
How do I do that?
I know that I can have a printout like:
public void printout() {
System.out.printf("Your name is: " + getName() +
" and you are a " + getSex());
}
This is a simple example to show you how to do it:
public class Person {
private String name;
private String gender;
private int age;
Person(String name, String gender, int age){
this.name = name;
this.gender = gender;
this.age = age;
}
public void setName(String name){
this.name = name;
}
public void setGender(String gender){
this.gender = gender;
}
public void setAge(int age){
this.age = age;
}
public String getName(){
return this.name;
}
public String getGender(){
return this.gender;
}
public int getAge(){
return this.age;
}
public static void main(String[] args)
{
Person me = new Person("MyName","male",20);
System.out.println("My name is:" + me.getName());
me.setName("OtherName");
System.out.println("My name is:" + me.getName());
}
}
This will print out:
My name is:MyName
My name is:OtherName
Let eclipse handler it for you
Click on your variable
Source > Generate Setter / Getter
You need to create an object of one class in the other class. You can then call the .get() and .set() methods on them. I will post an example in 2 minutes
First class (i'll call it Person) will have methods to return its fields
private String name = "";
private String age = 0;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
The second class will call those methods after it creates an object of the first class
bob = new Person("Bob", 21);
System.out.println("Your name is: " + bob.getName() +
" and you are " + bob.getAge());
The point of getters and setters is to let you limit/expand the scope or functionality of your property, independent of each other.
You may want your 'name' property to be readonly outside of your PersonInfo class. In this case, you have a getter, but no setter. You can pass in the value for the readonly properties through the constructor, and retrieve that value through a getter:
public class PersonInfo
{
//Your constructor - this can take the initial values for your properties
public PersonInfo(String Name)
{
this.name = Name;
}
//Your base property that the getters and setters use to
private String name;
//The getter - it's just a regular method that returns the private property
public String getName()
{
return name;
}
}
We can use getName() to get the value of 'name' outside of this class instance, but since the name property is private, we can't access and set it from the outside. And because there is no setter, there's no way we can change this value either, making it readonly.
As another example, we may want to do some validation logic before modifying internal values. This can be done in the setter, and is another way getters and setters can come in handy:
public class PersonInfo
{
public PersonInfo(String Name)
{
this.setName(Name);
}
//Your setter
public void setName(String newValue)
{
if (newValue.length() > 10)
{
this.name = newValue;
}
}
Now we can only set the value of 'name' if the length of the value we want to set is greater than 10. This is just a very basic example, you'd probably want error handling in there in case someone goes jamming invalid values in your method and complains when it doesn't work.
You can follow the same process for all the values you want, and add them to the constructor so you can set them initially. As for actually using this pattern, you can do something like the following to see it in action:
public static void main(String[] args)
{
PersonInfo myInfo = new PersonInfo("Slippery Sid",97,"male-ish");
var name = myInfo.getName();
System.out.printf("Your name is: " myInfo.getName() + " and you are a " myInfo.getSex());
myInfo.setName("Andy Schmuck");
System.out.printf("Your name is: " myInfo.getName() + " and you are a " myInfo.getSex());
}
You create an object by instantiating the constructor as follows
Personinfo pi = new Personinfo("Anna", "female", "17");
You can then call methods upon that object as follows
pi.setName("Alan");
or
pi.getName();
here's how you do it:
public class PersonInfo {
private String name;
private String sex;
private int age;
/** GETTERS **/
public String getName(){
return name;
}
public String getSex(){
return sex;
}
public int getAge(){
return age;
}
/** SETTERS **/
public void setName(String name){
this.name = name;
}
public void setSex(String sex){
this.sex = sex;
}
public void setAge(int age){
this.age = age;
}
}
class Test{
public static void main(String[] args){
PersonInfo pinfo = new PersonInfo();
pinfo.setName("Johny");
pinfo.setSex("male");
pinfo.setAge(23);
//now print it
System.out.println("Name: " + pinfo.getName());
System.out.println("Sex: " + pinfo.getSex());
System.out.println("Age: " + pinfo.getAge());
}
}
Or you can add this as well:
#Override
public String toString(){
return "Name: " + this.name + "\n" +
"Sex: " + this.sex + "\n" +
"Age: " + this.age;
}
and then just to a .toString
EDIT:
Add this constructor in the class to initialize the object as well:
public PersonInfo(String name, String sex, int age){
this.name = name;
this.sex = sex;
this.age = age;
}
In personInfo:
public Person(String n, int a, String s){
this.name=n;
this.age=a;
this.sex=s;
}
public String getName(){
return this.name;
}
public int getAge(){
return this.age;
}
public String getSex(){
return this.sex;
}
public void setName(String n){
this.name = n;
}
public void setAge(int a){
this.age = a;
}
public void setSex(String s){
this.sex = s;
}
Then fix the print statement:
System.out.println("Your name is: " + myInfo.getName() + " and you are a " + myInfo.getSex());