Hi, as I was told that my code doesn’t scale well at all, I thought perhaps I’d try to get a better understanding of interfaces/abstract classes and classes and the relationship between them.
I don’t want at this stage work on a big separate project as I've already got plenty to work on, rather do small exercises to help me understand the concept.
So, I was thinking, maybe I can create a small program that output the characteristics of either an employee or a client of an organisation, perhaps loop through them, just to better understand relationships between classes.
So, while I’m open to suggestions of course, here is the plan:
-create an abstract class Person, that has at least a name and a surname, perhaps a method returning a string
-create a class Employee that implements Person and that perhaps contains its own method (not sure which one at the moment, maybe something that prints "I'm a en employee")
-create a class Client that implements Person and that perhaps contains its own method (not sure which one at the moment, maybe something that prints "I'm a client")
How does that sound as a start?
Recommended Answers
Jump to PostOK, it's a start. Be careful with your terminology. If Person is a class then the others have to
extend
it. If it's an interface the othersimplement
it.
Chosing between an abstract superclass and an interface is often one of those difficult decisions. Chose a class and you prevent …
Jump to PostIf a class needs some variables initialised then an empty constructor is just asking for trouble. Obviously if you don't have one then you can't call
new
with no parameters, but that makes sense too. (Unless you are writing a factory class.)Normally every subclass would override
toString
, your printStatus …
Jump to PostI think salary belongs in Employee - only employees have a salary. This is typical of how a subclass can extend a superclass to add more info that's just relevant to the subclass.
Override
…toString
in all your classes. You can use the superclass's version to avoid repetition, eg
Jump to PostI get where you are coming from, but that extra info just looks like ordinary attributes of an employee to me, and not a good reason for another class. How about an Address class (street, postcode etc)
Jump to PostYou may have noticed that I has second thoughts and changed that suggestion to Address instead - it's easier to see what the attributes are. Projects are more independent, and may have multiple Employees, so it's not strictly speaking composition,.
All 31 Replies
We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.