So, I'm working on a homework assignment, and I'm having a hard time following some of the directions, I've pasted the assignment below:
Create a hierarchy of five classes, plus one class included as a variable inside:
Person has four String variables: name, address, phone, email
Student is a subclass to Person and has one additional int variable status which takes values of 1, 2, 3, or 4 representing freshman, sophomore, junior, senior
MyDate has three int variables for year, month, and day
Employee is a subclass to Person and has one String variable office, one int variable for salary, and one MyDate variable for dateHired
Staff is a subclass to Employee and has one additional String variable for title
Faculty is a subclass to Employee and has one additional String variable for rank which takes values of Professor, Associate Professor, Assistant Professor, Instructor, and Adjunct. The data for all six classes should be private.
As for methods, you can skip the normal setters and getters if you write a single constructor that has parameters for all data and override the toString( ) method. Constructors of subclasses should use the super class constructor. The toString( ) methods of subclasses should use the toString( ) method of their super class.
The part that throws me for a loop is the idea that a single constructor can be written that will cover all the necessary parameters for the setters and getters instead of writing them in each sub-class. Is this possible? And how so?
You need to use the constructor of the superclass whilst creating the subclass. So it should be:
public class Staff extends Employee {
private String title;
public Staff(String name, String address, String phone, String email, int status, String title) {
super(name, address, phone, email, status);
this.title = title;
}
}
Use the super(/*params of super class*/) to invoke the constructor of the super class and instantiate the inherited attributes. Note that you can only call a superclass constructor as the first statement of a constructor. If you don't call a superclass constructor explicitly, a call to super() (the default constructor of the superclass) is inserted automatically by the Java compiler.
For calling the parent class's toString() use:
public String toString() {
return super.toString() + " ,title : " this.title;
}
Similarly write the constructors and toString() methods of all classes.
As for methods, you can skip the normal setters and getters if you write a single constructor that has parameters for all data and override the toString( ) method.
I think the directions mean that each class you write can have a single constructor that takes parameters for all of its data. Taking the MyDate constructor for example:
public MyDate(int year, int month, int day) {
...
}
And likewise override toString() to report all that information.
Instead of writing
public class A {
private int b;
private int c;
public void setB(int b) {this.b = b;}
public int getB() {return b;}
// same for c
}
you allowed to code
public class A {
private int b;
private int c;
public A(int b, int c) {
this.b = b;
this.c = c;
}
#Override
public String toString() {
return "[b = " + b + ", c = " + c + "]";
}
(The implementation of toString() is just an example, it just needs to print the states of all fields)
This is what you can do
Person(String name,String address,String phone,String email){
//Person constructor
this.name = name;
this.address = address;
this.phone = phone;
this.email = email;
}
public String toString(){
//toString method
return "Name: "+name+" Address: "+address+" Phone: "+phone+" Email: "+email;
}
Related
I have the following problem. I have two classes - one is the base class and the pther is inheriting it. So in the parent class is an abstract class and it consists three fields - String name, String adress and int age. However in my task it says the value for age has to be set by default to be 25 years. My question is - How do implement this value with the help of inherited method setAge() in the constructor of the inherited class?
My abstract constructor looks like this:
public Student(String name, String adress, int age){
this.setName(name);
this.setAdress(adress);
this.setAge(age);
}
and setter:
public void setAge(int age){
this.age = age;
}
How do I do the implementation in the inherited class by using a default value?
If the superclass constructor takes three parameters in its constructor, and you have subclass with a constructor with only two parameters, you can call super to pass the two arguments plus a third default value to the constructor of the superclass.
public abstract class Person
{
// Constructor
public Person() ( String name, String address, int age )
{ …
And subclass.
public abstract class Student
{
// Constructor
public Person() ( String name, String address )
{
super( name , address , 25 ) ; // Default age of 25 for new `Student` objects.
…
This is a silly example as defaulting a person’s age would not happen in real work. But the concepts demonstrated are sound.
Im receiving that error when trying create a constructor for the second class. Do I need to use the same parameters for the second class as the first class?
class Person {
private String name;
private String gender;
private int phone;
protected Person(String n, String g, int p)
{name = n; gender = g; phone = p;}
public String toString(){return name +" "+gender+" "+phone;}
}
class Student extends Person {
private String subject;
private int sNumber;
protected Student(String s, int sn){subject = s; sNumber = sn;}
}
class Lecturer extends Person {
private String Department;
private int staffNo;
public Lecturer(String d, int stfNo){Department = d; staffNo = stfNo;}
}
Every extended class calls the super constructor first. In your Person class you have defined only a non default constructor therefore there is no default constructor.
Either provide a default constructor (constructor without any parameters) in Person or call the super constructor explicitly with super(name, gender, phone)
When compiled, your compiler will add super() as the first line of your childs constructor searching for the parent non arg constructor.
Since your parent class already has one using params, no default no arg constructor will be created at compile time.
Two solutions :
Add super(string,string,int) giving it the right parameters as the first line of your childs constructor
Create a Person() constructor taking no arguments so that super() finds something to call at compilation time.
If a class extends another class, it must call the constructor of that extended class.
Since you specified a constructor for Person you need to call it in Student and Lecturer as the first statement:
protected Student(String s, int sn, String n, String g, int p)
{
super(n, g, p);
subject = s;
sNumber = sn;
}
You might not have seen this error before, since the compiler automatically adds super(); as the first statement. Since this constructor does not exists (you specified your own) this does not work.
If you don't call the constructor of the super class you never initialize it.
Question:
Implement a super class Person. Make two classes, Student and Instructor
that inherit from Person. A person has a name and a year of birth. A student
has major and the instructor has a salary. Write the class declarations, the
constructors, and the methods to String for all classes. Write a test program
that tests these classes and methods.
This may not be a complicated one but i'm a beginner in java. Please help me.
I'm getting the following error at the both the constructors 'student()' and 'instructor()'.
"constructor Person in class Person cannot be applied to given types;
required: String,int
found: no arguments
reason: actual and formal argument lists differ in length."
Here's my code:
package One;
class Person{
String name;
int yob;
Person(String s, int d){
name = s;
yob = d;
}
#Override
public String toString(){
return "Name: "+name+"\n Year of Birth: "+yob;
}
}
class Student extends Person{
String major;
Student(String s){
major = s;
}
#Override
public String toString(){
return "The student did his majors in "+major;
}
}
class Instructor extends Person{
int salary;
Instructor(int a){
salary = a;
}
#Override
public String toString(){
return String.format("The salary is ",salary);
}
}
public class Test {
public static void main(String[] args) {
Person p = new Person("Stephen", 1991);
System.out.println(p);
}
}
Thanks in advance.
In your code, the classes Student and Instructor derive from Person. This means that any constructor parameters needed by the base class are also needed by the derived class. When you create a Student, how will the compiler know what to put in the parameters of the Person constructor?
So the code should be like this:
// Student constructor
Student(String majorParam, String nameParam, int yobParam)
{
super(nameParam, yobParam);
this.major = majorParam;
}
...
// Similarly, Instructor constructor
Instructor(int salaryParam, String nameParam, int yobParam)
{
super(nameParam, yobParam);
salary = salaryParam;
}
Notice how we are transferring the constructor parameters required by the base class Person using the super constructor keyword. This always has to be the first line in the derived class constructor.
Then you can construct Student and Instructor as:
Student s = new Student("TheMajor", "TheName", 42);
Instructor i = new Instructor(1000, "TheName", 42);
There is no empty constructor in Person class, so you have to create that and it should work perfectly. Don't forget that super() is called by default unless explicitly called.
package wr3;
public class Person {
private String name;
private String id;
private String bday;
private String address;
public String getName(){
return name;
}
public String getID(){
return id;
}
public String getBday(){
return bday;
}
public String getAdd(){
return address;
}
public void equals(){
super.equals(id);
}
#Override
public String toString(){
return(name + bday + id + address);
}
}
package wr3;
public class Test {
public static void main(String[] args){
String name = "Claude Rhay Torre";
String name2 = "Bea Señerpida";
String id = "10302993";
String id2 = "11102825";
String bday = "06/201993";
String bday2 = "11/17/1994";
String address = "BF Better Living Basak LLC";
String address2 = "F Martyr St Poblacion LLC";
boolean eq;
System.out.println(name.toString());
System.out.println(id.toString());
System.out.println(bday.toString());
System.out.println(address.toString());
System.out.println();
System.out.println(name2.toString());
System.out.println(id2.toString());
System.out.println(bday2.toString());
System.out.println(address2.toString());
eq = id.equals(id2);
System.out.println("\nDo they have the same ID number? " + eq );
}
}
So I have this code.
And I also have this problem.
A. Object class
Study the Object class in the java.lang package.
Understand all its methods.
Create a Person class with the requirements:
a. Implement encapsulation
b. The fields are: name, ID (identification number), birthday, and
address.
c. A method that will override the equals( ) method of Object class.
Two persons are equal if they have the same id.
d. A method that will override the toString( ) method of Object
class. It displays the id, name, birthday, and address of a Person
object.
Create a test class to create Person objects and call the equals( ) and toString( ) methods appropriately.
My question is, are these two classes even related?
What I mean, is my "toString" and "equal" method called on my Test class the one that is in my Person's class? Or is it the "toString" and "equal" methods on the Object class?
How can I override the equals and toString class in the Object class?
When inheriting a method from another class (such as public String toString() from Object), all you have to do to override it is define your own public String toString() in your class. You have actually done that in your code and you have successfully overridden toString() for all instances of Person.
The reason you're not seeing the result you might expect is that the toString() and equals() methods you are calling are from the String class, not from your Person class. This is because you are calling them on String objects, not Person objects - and those two classes are not related hierarchically (apart from their common Object ancestor).
Your Test could be like this, instead:
Person p1 = new Person();
p1.name = "Claude Rhay Torre";
p1.id = "10302993";
p1.bday = "06/20/1993";
p1.address = "BF Better Living Basak LLC";
Person p2 = new Person();
p2.name2 = "Bea Señerpida";
p2.id2 = "11102825";
p2.bday2 = "11/17/1994";
p2.address2 = "F Martyr St Poblacion LLC";
System.out.println(p1.toString());
System.out.println(p2.toString());
This question already has answers here:
What is the meaning of "this" in Java?
(22 answers)
Closed 7 years ago.
I was studying method overriding in Java when ai came across the this keyword. After searching much about this on the Internet and other sources, I concluded that thethis keyword is used when the name of an instance variables is same to the constructor function
parameters. Am I right or wrong?
this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):
class Foo
{
private int bar;
public Foo() {
this(42); // invoke parameterized constructor
}
public Foo(int bar) {
this.bar = bar; // disambiguate
}
public void frob() {
this.baz(); // used "just because"
}
private void baz() {
System.out.println("whatever");
}
}
this keyword can be used for (It cannot be used with static methods):
To get reference of an object through which that method is called within it(instance method).
To avoid field shadowed by a method or constructor parameter.
To invoke constructor of same class.
In case of method overridden, this is used to invoke method of current class.
To make reference to an inner class. e.g ClassName.this
To create an object of inner class e.g enclosingObjectReference.new EnclosedClass
You are right, but this is only a usage scenario, not a definition. The this keyword refers to the "current object". It is mostly used so that an object can pass itself as a parameter to a method of another object.
So, for example, if there is an object called Person, and an object called PersonSaver, and you invoke Person.SaveYourself(), then Person might just do the following: PersonSaver.Save( this );
Now, it just so happens that this can also be used to disambiguate between instance data and parameters to the constructor or to methods, if they happen to be identical.
this keyword have following uses
1.used to refer current class instance variable
class Student{
int id;
String name;
student(int id,String name){
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student s1 = new Student(111,"Karan");
Student s2 = new Student(222,"Aryan");
s1.display();
s2.display();
}
}
here parameter and instance variable are same that is why we are using this
2.used to invoke current class constructor
class Student{
int id;
String name;
Student (){System.out.println("default constructor is invoked");}
Student(int id,String name){
this ();//it is used to invoked current class constructor.
this.id = id;
this.name = name;
}
void display(){System.out.println(id+" "+name);}
public static void main(String args[]){
Student e1 = new Student(111,"karan");
Student e2 = new Student(222,"Aryan");
e1.display();
e2.display();
}
}
3.this keyword can be used to invoke current class method (implicitly)
4.this can be passed argument in the method call
5.this can be passed argument in the constructor call
6.this can also be used to return the current class instance
This refers current object. If you have class with variables int A and a method xyz part of the class has int A, just to differentiate which 'A' you are referring, you will use this.A. This is one example case only.
public class Test
{
int a;
public void testMethod(int a)
{
this.a = a;
//Here this.a is variable 'a' of this instance. parameter 'a' is parameter.
}
}
Generally the usage of 'this' is reserved for instance variables and methods, not class methods ...
"class methods cannot use the this keyword as there is no instance for
this to refer to..."
http://docs.oracle.com/javase/tutorial/java/javaOO/classvars.html
Here's a trivial example ...
public class Person {
private String name;
private int age;
private double weight;
private String height;
private String gender;
private String race;
public void setName( String name ) {
this.name = name;
}
public String getName() {
return this.name;
}
public void setAge( int age) {
this.age = age;
}
public int getAge(){
return this.age;
}
public void setWeight( double weight) {
this.weight = weight;
}
public double getWeight() {
return this.weight;
}
public void setHeight( String height ) {
this.height = height;
}
public String getHeight() {
return this.height;
}
public void setGender( String gender) {
this.gender = gender;
}
public String getGender() {
return this.gender;
}
public void setRace( String race) {
this.race = race;
}
public String getRace() {
return this.race;
}
public void displayPerson() {
System.out.println( "This persons name is :" + this.getName() );
System.out.println( "This persons age is :" + this.getAge() );
System.out.println( "This persons weight is :" + this.getWeight() );
System.out.println( "This persons height is :" + this.getHeight() );
System.out.println( "This persons Gender is :" + this.getGender() );
System.out.println( "This persons race is :" + this.getRace() );
}
}
And for an instance of a person ....
public class PersonTest {
public static void main( String... args ) {
Person me = new Person();
me.setName( "My Name" );
me.setAge( 42 );
me.setWeight( 185.00 );
me.setHeight( "6'0" );
me.setGender( "Male" );
me.setRace( "Caucasian" );
me.displayPerson();
}
}
In case of member variable and local variable name conflict, this key word can be used to refer member variable like,
public Loan(String type, double interest){
this.type = type;
this.interest = interest;
}
if you have knowladge about c,c++ or pointers, in that language this is a pointer that points object itself. In java everything is reference. So it is reference to itself in java. One of the needs of this keyword is that:
Think that this is your class
public class MyClass
{
public int myVar;
public int myMethod(int myVar)
{
this.myVar = myVar; // fields is set by parameter
}
}
If there is not this keyword you it is confused that this is paramter or class field.When you use this.myVar it refers field of this object.
I would like to modify your language. The this keyword is used when you need to use class global variable in the constructors.
public class demo{
String name;
public void setName(String name){
this.name = name; //This should be first statement of method.
}
}
this is a reference to the current object — the object whose method or constructor is being called. You can refer to any member of the current object from within an instance method or a constructor by using this.
One more thing that should be in mind is that this keyword might be the first statement of your method.
This is used in java. We can use in inheritance & also use in method overloading & method overriding. Because the actual parameter or instance variable name has same name then we can used this keyword complsary . But some times this is not same as when we can not use this keyword complsary.....
Eg:- class super
{
int x;
super(int x)
{
this.x=x
}
}