Constructor two classes up java - java

I am trying to access a constructor in an abstract class that is two levels higher.
public abstract class Person{
protected String name;
public Person(String name){
if name.length() <= 12)
this.name = name;
else
this.name = name.substring(0,12);
}
public final String returnName(){
return name;
}
}
public class employee extends person{
public employee(string firstname, string gender){
super(firstname);
this.gender =gender;
}
}
public class dependent extends employee{
public dependent(string firstname, string gender, string relation){
super(firstname);
super(gender);
this.relation = relation;
}
How do I invoke the constructor of the abstract class from the dependent class (two levels below)?

Ok, first of all, here's how you pass two parameters to your Employee constructor:
super(firstname, gender);
Second, there's no need to call the Person constructor from the Dependent one. This will happen automatically when Dependent calls the Employee constructor, because the Employee constructor then calls the Person one.

What you are looking for is something like the below, please note Classes start with Upper-case and camel case for method parameter staring with a lower-case letter. String must be upper-case String name , please also be aware you have introduced a protected member scope on name
See the following post on the implications In Java, difference between default, public, protected, and private
public abstract class Person
{
protected String name;
public Person(String name)
{
if (name.length() <= 12)
{
this.name = name;
}
else
{
this.name = name.substring(0, 12);
}
}
public final String returnName()
{
return name;
}
}
public class Employee extends Person
{
private String gender = null;
public Employee(String firstName, String gender)
{
super(firstName);
this.gender = gender;
}
}
public class Dependent extends Employee
{
private String relation = null;
public Dependent(String firstName, String gender, String relation)
{
super(firstName, gender);
this.relation = relation;
}
}
You will need to add methods to access the relation and gender if you need the access to these

try this:
public class employee extends Person{
public employee(String firstname, String gender){
super(firstname);
this.gender =gender;
}
}
public class dependent extends employee{
public dependent(String firstname, String gender, String relation){
super(firstname,gender);
this.relation = relation;
}

Related

Refactoring in Java: Duplicated attributes

I am supposed to refactor duplicated attributes in Student class. I have Student and Professor classes as below. I am really confused about how to do refactoring with attributes. Should I add a new class, or made modifications in one of the classes. If so, how? I could not understand how to proceed with this to-do.
private final String matrNr;
private final String name;
private final int age;
private int semester;
private final String email;
public Student(String name, int age, String email, String matrNr, int semester) {
this.matrNr = matrNr;
this.name = name;
this.age = age;
this.semester = semester;
this.email = email;
}
public String getEmail() {
return email;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
public int getSemester() {
return semester;
}
public String getMatrNr() {
return matrNr;
}
public void increaseSemester(){
semester = semester + 1;
}
}
And the professor is a like:
private final String persNr;
private final String name;
private final int age;
private final String email;
public Professor(String name, int age, String email, String persNr) {
this.persNr = persNr;
this.name = name;
this.age = age;
this.email = email;
}
public int getAge() {
return age;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public String getPersNr() {
return persNr;
}
}
Thanks for any kind of helps!
Your goal is to refactor duplicated attributes in the Student and Professor classes. The way to do this is to create a parent class which defines the common attributes (like "name"), and modify Student and Professor classes to extend the common parent class. In this way, both Students and Professors can have a "name", even though you have defined "name" only once in the common parent.
Below shows how you could do this with a common "Human" parent class, how the constructors would work, and how you could define a Student-only attribute (semester).
Here is a simple version a common Human class:
common "Human" class
each Human has a "name"
the name is set in the constructor (so when you're creating an object) and cannot be changed later ("name" is final; also no "setHuman()")
class Human {
private final String name;
public Human(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Here's a simple Professor class:
by definition, a Professor is a Human (Professor extends Human)
when creating a Professor, you must specify the "name" (which is then passed to the Human constructor)
once you have a Professor, you can call getName() (which is defined on the Human class)
class Professor extends Human {
public Professor(String name) {
super(name);
}
}
Here's a simple Student class:
Student is a little different - in addition to a name, it also has a "semester"
when creating a Student, the constructor requires a name and semester, and the Student class itself keeps track of "semester" – so it's fine to have semester defined on Student, and name defined on Human.
you can call getName() (defined on Human)
you can call getSemester() (defined on Student)
class Student extends Human {
private final int semester;
public Student(String name, int semester) {
super(name);
this.semester = semester;
}
public int getSemester() {
return semester;
}
}

how to replace an email in java through a method

first time I've tried this. I need to be able to replace an email for subclass Student and sublass Teacher after an email has been inputted, I have a parent class and superclass which is where I believe I need to add my changeEmail method. I may be a way off here but can I use stringBuilder or is there an easier way? Real noob when it comes to this.
SUBCLASS -
public class Teacher extends Member
{
private String qualifications;
public Teacher(String name, String email, String qualifications)
{
super(name, email);
this.qualifications = qualifications;
}
public String getQualifications()
{
return qualifications;
}
public String toString()
{
StringBuffer details = new StringBuffer();
details.append(super.getName());
details.append(' ');
if(qualifications != null && qualifications.trim().length() > 0) {
details.append("(" + qualifications + ")");
details.append(' ');
}
details.append(super.getEmail());
return details.toString();
}
}
SUBCLASS -
public class Student extends Member
{
private int attendance;
public Student(String name, String email)
{
super(name, email);
this.attendance = 0;
}
public int getAttendance()
{
return attendance;
}
public void markAttendance(int attendance)
{
this.attendance += attendance;
}
public void print()
{
System.out.println(super.getName() + " (" + attendance + ")");
}
}
SUPERCLASS -
public class Member
{
private String email;
private String name;
public Member(String name, String email)
{
this.name = name;
this.email = email;
}
public String getEmail()
{
return email;
}
public String getName()
{
return name;
}
public String changeEmail()
{
//..........
}
}
Since changeEmail is a public method in the superclass, the subclasses can access it too. Student (as well as Teacher) is a Member.
public String changeEmail(String newEmailAddress) {
String old = email;
this.email = newEmailAddress;
return old;
}
What I changed was adding a parameter (String newEmailAddress) and then set the new value to the email instance field.
(EDIT: I updated the answer to return the old email address. I don't know why a method like this would return anything but anyways..)
That is called inheritance, basically if you have some shared variables, you can use some parent class and with the keyword extends create some subclasses.
All subclasses, which inherits the parent class, can have their own class variables, but also are having the parent variables.
In your case you can image the diagram like that- obvious, doesnt?
So...
Parent class member is having these class variables:
- String : mail
- String : name
You have two subclasses- Student and Teacher:
Teacher class variables:
qualifications
mail, name (inherited from parent!)
Student class variables:
attendance
mail, name (inherited from parent!)
Notice- with the keyword super you are calling the constructor (or simply "class" other methods) from the parent, so in Teacher and Student class, you will call exactly following:
public Member(String name, String email) {
this.name = name;
this.email = email;
}
To be able change the email, you need following
1) implement methods in parent class
2) optional- add call to child classes, and for usage outside the class also add some external method (without this you can still use public parent class methods)
Eg.
in parent
public void changeEmail(String newEmail) {
this.email = newEmail;
}
public String changeEmailWithReturnOld(String newEmail) {
String oldMail = this.email;
changeEmail(newEmail); //calling above
return oldMail;
}
In childs
public String changeTheMailWithReturnOld(String newMail) {
return super.changeEmailWithReturnOld(newMail); //super means super class, parent
}
Clear? :)
Then you can call following:
Teacher teacher1 = new Teacher("foo", "foo#foo.foo", "whateverFoo");
teacher1.changeEmail("someNewFoo#foo.foo"); //parent method
teacher1.changeEmailWithReturnOld("someNewFoo#foo.foo"); //Child method

java Having multiple constructors for superclass

I have a superclass with 3 constructors and I want to know if there is a smarter way to write subclass constructors
public class Person{
private String name;
private int age;
private String homeTown;
public Person(String name){
this.name = name;
this.age = 18;
this.homeTown = "Atlanta";
}
public Person(String name, int age){
this.name = name;
this.age = age;
this.homeTown = "Atlanta";
}
public Person(String name, int age, String homeTown){
this.name = name;
this.age = age;
this.homeTown = homeTown;
}
I also have a subclass that inherits superclass
public class Student extends Person{
private double avgGPA;
private int ID;
private String[] classes;
public Student(double avgGPA, int ID, String[] classes, String name){
super(name);
this.avgGPA = avgGPA;
this.ID = ID;
this.classes = classes;
}
public Student(double avgGPA, int ID, String[] classes, String name, int age){
super(name, age);
this.avgGPA = avgGPA;
this.ID = ID;
this.classes = classes;
}
public Student(double avgGPA, int ID, String[] classes, String name, int age, String homeTown){
super(name, age, homeTown);
this.avgGPA = avgGPA;
this.ID = ID;
this.classes = classes;
}
My subclass works fine and runs without an error, but I want to know if there is another way to write a constructor for the subclass without writing the same constructor 3 times, just because the super class has 3 different constructors.
Well, there is something in Java to simplify your superclass. You can invoke another constructor in the same class using this();. So, instead of setting each variable for each constructor, use one variable-setting constructor and use this(); to pass it defaults. For your superclass, you could use these instead:
public Person(String name){
this(name, 18, "Atlanta");
}
public Person(String name, int age){
this(name, age, "Atlanta");
}
public Person(String name, int age, String homeTown){
this.name = name;
this.age = age;
this.homeTown = homeTown;
}
For the subclass, I'd create a private method called setVars which takes in the three variables you'd use: double avgGPA, int ID, and String[] classes. So, instead of setting them in each constructor, your class could look like this:
public Student(double avgGPA, int ID, String[] classes, String name){
super(name);
setVars(avgGPA, ID, classes);
}
public Student(double avgGPA, int ID, String[] classes, String name, int age){
super(name, age);
setVars(avgGPA, ID, classes);
}
public Student(double avgGPA, int ID, String[] classes, String name, int age, String homeTown){
super(name, age, homeTown);
setVars(avgGPA, ID, classes);
}
private void setVars(double avgGPA, int ID, String[] classes) {
this.avgGPA = avgGPA;
this.ID = ID;
this.classes = classes;
}
I think that's about as efficient as you'd get, unless you want to create a static initialization method as QueenSvetlana's answer recommended.
Something along the lines of this:
public final class Person{
private final String name;
private final int age;
private final String homeTown;
private double avgGPA;
private Person(String name, int age, String homeTown, avgGPA){
this.name = name;
this.age = age;
this.homeTown = homeTown;
this.avgGPA = avgGPA;
}
public static Person createPerson(String name, age, homeTown, avgGPA){
return new Person(name, age, homeTown, avgGPA);
}
public static Person createPersonwithoutHomeTown(String name, age,avgGPA){
return new Person(name, age, "Atlanta", avgGPA);
}
public static Person createPersonwithoutAge(String name,avgGPA){
return new Person(name, 18, "Atlanta", avgGPA);
}
}
Immutable objects are objects that don't change their state after creation, and don't allow for sub classing. In the long run, immutable classes are favorable.
I think modifying your Person object to use a builder-pattern would help you.

Java ,import not resolved,inheritance,inner class

Begging java programming recently, run into an error. please help
Have two classes , PersonTest.java:
public class PersonTest {
public static void main(String[] args) {
Person person1=new Person("dummy","sdymmt","20","male","washington");
System.out.println("Name: "+person1.getName());
System.out.println("Surname: "+person1.getSurname());
System.out.println("Age: "+person1.getAge());
System.out.println("Gender:" +person1.getGender());
System.out.println("Birthplace: "+person1.getBirthplace());
Person person2= new Person(400);
System.out.println("Income:"+person2.getX()+" mije leke");
System.out.println("Tax:"+person2.Taksat()+" mije leke");
Student student1= new Student("adsd","zedsdsadza");
System.out.println("emri"+student1.getEmer());
}
}
and also Person.java :
public class Person {
private String Name;
private String Surname;
private String Age;
private String Gender;
private String Birthplace;
private double x;
public Person()
{
}
public Person(String Name, String Surname, String Age, String Gender, String Birthplace) {
this.Name = Name;
this.Surname = Surname;
this.Age = Age;
this.Gender = Gender;
this.Birthplace = Birthplace;
}
public String getName() {
return Name;
}
public String getSurname() {
return Surname;
}
public String getAge() {
return Age;
}
public String getGender() {
return Gender;
}
public String getBirthplace() {
return Birthplace;
}
public Person(double x) {
this.x = x;
}
public double getX() {
return x;
}
double Taksat() {
return (0.1 * x);
}
public class Student extends Person {
private String University;
private String Faculty;
public Student(String Universiteti, String Fakulteti) {
super(Name, Surname, Age, Gender, Birthplace);
this.Faculty = Fakulteti;
this.University = Universiteti;
}
public String getFaculty() {
return Faculty;
}
public String getUniversity() {
return University;
}
}
}
Two classes are in the same default package. How to fix the fact that the test class doesn't recognize the inner class student as a class.
Nested non static class are called Inner Classes those classes cannot live without the Outer class (which wrapped them).
Java docs
An instance of InnerClass can exist only within an instance of
OuterClass and has direct access to the methods and fields of its
enclosing instance.
To instantiate an inner class, you must first instantiate the outer
class. Then, create the inner object within the outer object with this
syntax:
OuterClass.InnerClass innerObject = outerObject.new InnerClass();
Try using:
Person.Student student = person1.new Student(PARAMETERS);
Important Mark:
Of course, you should highly consider that this is not a good design, because you may want this classes to be visible outside of the Person class but also because Person.Student inherits from Person, which it's already contains the Student class, which usually looks like a loop or a circle relationship, which usually not a good idea for the first place.
Because there is no Student class. Since it nested, it's Person.Student

issue with multiple inheritance in Java

I would like to model the following classes in Java:
so I came with the following code:
class Person
{
private String name;
private ing age;
public Person(String name, int age){
this.name=name;
this.age=age;
}
//set and get methods
}
class Employee
{
private String nameEmp;
private double salary;
public Employee(String nameEmp, double salary){
this.nameEmp=nameEmp;
this.salary=salary;
}
public double calcSalary(){} //should this be an abstract method?
}
class Teacher extends Person implements Employee
{
private String nameTeacher;
private int ageTeacher;
private String title; //professor or lecturer
public Teacher(String nameTeacher,int ageTeacher, String title){
super(nameTeacher,ageTeacher);
this.title=title;
}
public double calcSalary(){
if (title.equals("Professor")) salary=salary*0,30;
else if (title.equals("Lecturer")) salary=salary*0,10;
}
}
I would like to model it using interfaces, but I am not quite sure how to do it. Also the calcSalary should be an abstract method in Employee? How this can be implemented with interfaces in Java?
Thanks
No, you can't do it this way, you should go for Teacher is -> Employee is -> Person. You can't implement anything in interface! Interface can only contain methods that should be implemented by class.
You could have this:
public interface Person{
// Only abstract methods here
}
public interface Employee extends Person {
// Only abstract methods here specific to Employee
}
public class Teacher implements Employee {
//Implements the methods
}
Java 8 will allow you to place default implementations in interfaces. Until then, interfaces cannot contain implementations.
Start with Person. You had a typo there:
public class Person
{
private String name;
private int age;
public Person(String name, int age){
this.name=name;
this.age=age;
}
// set and get methods, equals, hashCode, toString,
// perhaps an id for database storage.
}
Now, some Persons are Employees; others are students, parents, prospective students, and so on. If any method of Employee has an implementation, it can't be an interface. And in any case, having nameEmp is wrong since it will duplicate the name in Person. Either you create an interface for Employee that gets mixed into the Teacher class, or you inherit from Employee.
Either:
public interface Employee {
// Currency values should use BigDecimal or BigInteger, not double.
BigDecimal salary();
// Taxpayer Identification Number (SSN) in the USA, or the equivalent outside.
String taxNumber();
}
or:
public class Employee extends Person {
private BigDecimal salary;
private String taxNumber;
public Employee(String name, int age, BigDecimal salary,
String taxNumber) {
super(name, age);
this.salary = salary;
this.taxNumber = taxNumber;
this.title = title;
}
// getters, setters, etc.
}
public class Teacher extends Employee {
private Department department;
private List<Course> courses = new ArrayList<>();
// Constructors, getters, setters, etc.
}
You should only have the salary methods in Teacher if they need a wildly-different implementation. You might want to have some sort of pay calaculator class (the Strategy pattern) in the Employee class instead. This way you can handle taxable deductions, insurance, pension plans, overtime where applicable. I didn't understand the multipliers in your original example.
public interface Person {
String getName();
void setName(String name);
int getAge();
void setAge(int age);
}
public class PersonImpl implements Person {
private String name;
private int age;
#override public String getName() { return this.name; }
#override public void setName(String name) { this.name = name; }
#override public int getAge() { return this.age; }
#override public void setAge(int age) { this.age = age; }
}
public interface Employee extends Person {
double getSalary();
void setSalary(double salary);
double calcSalary();
}
public abstract class EmployeeImpl extends PersonImpl implements Employee {
private double salary;
#override public double getSalary() { return this.salary; }
#override public void setSalary(double salary) { this.salary = salary; }
}
public class Teacher extends EmployeeImpl
#override public double calcSalary() {
if (title.equals("Professor")) salary=salary*0,30;
else if (title.equals("Lecturer")) salary=salary*0,10;
}
}

Categories

Resources