This is the Image that I'm going to transfer from UML to Java, I don't know how to lock them together and i don't know how to make one bankAccount locked to only one person.
How do i connect the 2 classes??
Here is my code so far
My main method
public class Upp5 {
public static void main(String[] args) {
Person2 david = new Person2();
BankAccount acc1 = new BankAccount();
BankAccount acc2 = new BankAccount();
david.setName("David");
david.setPnr("551012-8978");
acc1.setBnr("37");
acc2.setBnr("38");
System.out.println("Namn: " + david.getName() + " \nPersonnummer:" + david.getPnr());
System.out.println(acc1.getBnr() + "\n" + acc2.getBnr());
}
}
BankAccount.java:
public class BankAccount {
private String bnr;
private double balance;
public void credit() {
}
public void withdraw(){
}
public String getBnr(){
return bnr;
}
public void setBnr(String newAccount){
bnr = newAccount;
}
public void createAccount(String newNbr){
bnr = newNbr;
}
}
and Person2.java
public class Person2 {
private String pnr;
private String name;
//Koppla konto till pnr
public void addAccount(BankAccount a){
}
//Skapa Pnr och Namn
public void setPnr(String newPnr) {
pnr = newPnr;
}
public void setName(String newName){
name = newName;
}
// Hämta Pnr och Namn
public String getPnr(){
return pnr;
}
public String getName(){
return name;
}
}
You need to define a List<BankAccount> to your Person2 entity:
public class Person2 {
private String pnr;
private String name;
// list of bank accounts (from 0 to n) the Person can have.
private List<BankAccount> accounts;
//Koppla konto till pnr
public void addAccount(BankAccount a){
if (accounts = null) accounts = new ArrayList<BankAccount>();
accounts.add(a);
}
//Skapa Pnr och Namn
public void setPnr(String newPnr) {
pnr = newPnr;
}
public void setName(String newName){
name = newName;
}
// Hämta Pnr och Namn
public String getPnr(){
return pnr;
}
public String getName(){
return name;
}
// include getters setters
}
EDIT1: as suggested by #NathanCastlehow if you want double relationship, BankAccount.java must have a Person2 attibute
public class BankAccount {
private String bnr;
private double balance;
// one bank account can only be owned by a single Person
private Person2 person;
public void credit() {
}
public void withdraw(){
}
public String getBnr(){
return bnr;
}
public void setBnr(String newAccount){
bnr = newAccount;
}
// generate getters setters
public Person2 getPerson(){
......
}
}
You didn't put any arrows in your diagram, so we don't know if the bankaccount knows the person it is linked to. The most logical thing to do is; let the Person have a List which you always initiate in the Person's constructor.
If you want the bankaccount to know the person that owns him (which seems logical to me), let the Bankaccount have the property "Person owner" and let the constructor be require a Person to exist. I don't understand why you have made a Person2 instead of a Person class.
Tips for you: Never (!!!) use parameters like; 'a' or properties like 'nBr' because other people wanna see in an instance what they are instead of guessing. :-) And try to make some security rules (that's why I put booleans in the classes).
Solution:
Person:
public class Person {
List<BankAccount> bankAccounts;
private String name;
private String pNbr;
public Person(String name, String pNbr) {
this.name = name;
this.pNbr = pNbr;
}
public void addAccount(BankAccount newAccount){
bankAccounts.Add(newAccount);
}
}
Bankaccount:
public class BankAccount {
private String nBr; //maybe make this final?
private double balance;
private Person owner;
public BankAccount(String nbr, Person owner) {
this(nbr, 0, owner); // If you also want to support new empty accounts
}
public BankAccount(String nbr, double balance, Person owner) {
this.name = name;
this.pNbr = pNbr;
this.owner = owner;
}
public boolean Credit(double amount)
{ // TODO: write code
boolean result = false;
return result;
}
public boolean Withdraw(double amount)
{ // TODO: write code
boolean result = false;
return result;
}
}
So generally when this is done in models such as a relational model you would have an association class. So a class that has like an ID from a bank account and an ID of the person. You can lock variables using the final keyword in front of them which forces them to only be initialized once.
The easiest way to "link" classes in java is to add one of said classes as an attribute. For example:
// Make it private to maintain encapsulation
private BankAccount myBankAccount;
But this only works if you have a 1..1 (One to one) relationship.
Your UML diagram indicates a 1..n (One to many) relationship between Person and BankAccount classes. In other words,
A Person may have multiple BankAccounts.
This means you'll a have to use a structure to "keep" multiple BankAccounts in a single Person. Java already provides you with some handy classes:
ArrayList: Easy, quick, insertion-ordered list. Allows as many itens as you need.
Hashmap: Hash implementation of the Map interface. Provides a way to find itens using a "key" (Ex: An account's number). Very efficient.
A suggest reading some of those classes documentation. And you can always look for some neat examples on the internet ;)
Related
If I have two classes, Player and BankAccount. When a player object is created using a constructor, a bank account object is automatically created and assigned with the same "ID" as the player object. How would I get a player's bank account if I created a new player and called it "player1"?
For example, how would I achieve player1.getBankAccount(); and be able to return the balance using the getter than I created in the BankAccount class? Like somehow use the player's 'ID', and get their bankaccount from it.
Thank you, sorry if this doesn't make much sense.
Player Class:
public Player(String name, BankAccount b, int id) {
this.name = name;
this.id = id;
BankAccount bank = new BankAccount(); // assigning a NEW bank
account for
a new player when a player object is created
}
Bank Account class:
public BankAccount(Player p, double balance) {
this.p = p;
this.balance = 10000.00;
}
Please at least try to use inheritance & poly. For example, your base class could be BankAccount with a getter to access the balance:
public class BankAccount
{
private double balance;
public BankAccount(double balance)
{
this.balance = balance;
}
public double getBalance()
{
return balance;
}
}
Then create Player as a child class inheriting from BankAccount:
public class Player extends BankAccount
{
private String name;
private int id;
public Player(String name, int id)
{
super(10000.00);
this.name = name;
this.id = id;
}
}
Then access the getter inherited from BankAccount:
Player player1 = new Player("playerName", 1234567);
player1.getBalance();
To do the other thing..."Like somehow use the player's 'ID', and get their bankaccount from it." , you could try something where as long as the instance of Player contains the id parameter or whatever parameter, it will return your other fields. Of course in your example the id is always required, so this only makes sense where you have overloaded the constructor to make it "optional":
public class Player extends BankAccount
{
private String name;
private String id;
//Constructors
public Player(String name, String id)
{
super(10000.00);
this.name = name;
this.id = id;
}
public Player(String name)
{
super(10000.00);
this.name = name;
}
//Public method
public String validateInstance(Player player)
{
if(player.id.isEmpty())
{
return "the instance has no id";
}
return getDetails();
}
//Getters
private String getDetails()
{
return (getName() + " " + getId());
}
private String getName()
{
return name;
}
private String getId()
{
return id;
}
}
Then use it like this for example:
player1.validateInstance(player1)
You should be able to tweak this approach to achieve exactly what you want.
I have a small assignment on adding and displaying different types of employees(diff. departments) at work and different salary & benefits, using OOP approach. I am quite not sure if my code is correct in terms of code reuse & if did I really meet the OOP coding approach...So far I have displayed 1 employee each type/department, I made them as a class name.(see code below). My question is if I add a new employee I'm going to declare another object of type Employee again. And what if there will be a lot of employees, I will be having a lot of objects. How do I lessen that and may I know if my OOP coding approach is correct so far? Ty very much! Here is my code:
//this is my parent class which implements an interface...
public abstract class Employees implements ICompensation{
private String fname;
private String lname;
private char gender;
private String address;
private double salary;
public String getfname(){
return this.fname;
}
public void setfname(String fname){
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public char getGender() {
return gender;
}
public void setGender(char gender) {
this.gender = gender;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
}
// this is a Developer type of employee
public class Developer extends Employees{
public Developer(String fname,String lname, char gender,String address, double salary){
setfname(fname);
setLname(lname);
setGender(gender);
setAddress(address);
setSalary(salary);
}
#Override
public double calculateSalary() {
double salary = getSalary();
salary += 10;
return salary;
}
#Override
public void print() {
System.out.println(this.getClass());
System.out.println(this.getfname());
System.out.println(this.getLname());
System.out.println(this.getGender());
System.out.println(this.getAddress());
System.out.println(this.calculateSalary());}}
//this is QA type of employee
public class QA extends Employees{
public QA(String fname,String lname,char gender,String address,double salary) {
setfname(fname);
setLname(lname);
setGender(gender);
setAddress(address);
setSalary(salary);
}
#Override
public double calculateSalary() {
double salary = getSalary();
salary = salary + 20;
return salary;
}
#Override
public void print() {
System.out.println(this.getClass());
System.out.println(this.getfname());
System.out.println(this.getLname());
System.out.println(this.getGender());
System.out.println(this.getAddress());
System.out.println(this.calculateSalary());
}
}
I have another 2 classes which are BA & Manager class but I wont include here because it's just have the same contents to the other derived class.
//so here is my Interface
public interface ICompensation {
double calculateSalary();
void print();
}
//and here is my main method.
import java.util.*;
public class main {
public static void main(String[] args){
Employees dev = new Developer("Janel","Logrono",'M',"Alabang",491);
Employees qa = new QA("juan","Sir",'M',"Taguig",1240);
Employees ba = new BA("pedro","Lyn",'F',"Taguig",1150);
Employees manager = new Manager("sebastian","rods",'M',"USA",555399);
ArrayList<Employees> ls = new ArrayList<>();
ls.add(dev);
ls.add(qa);
ls.add(ba);
ls.add(manager);
for(Employees e : ls){
e.print();
System.out.println();
}
}
}
How do add another employee w/o declaring a lot of objects and may I know if my OOP coding approach is correct so far, I think there are a lot of redundant codes here, how to lessen it? thx!
First of all you should not implements ICompensation in the bean class. Bean class will only contain getters, setters & constructor. You need to create another class which will implement the ICompensation. There you will write the code for calculations and other methods.
In database you can add another column "Role" which will define the employee role. By this approach you don't need to create extra methods such as QA, Developer, Manager.
please look into the following link. Here they tried to develop a login page using MVC model. You can just ignore the jsp pages and concentrate on controllers and beans.
https://krazytech.com/programs/a-login-application-in-java-using-model-view-controllermvc-design-pattern
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
What i want to do is store some instances of my class on a list and get a specific instance from that list.
This is an example of a custom class
public class Person
{
private String name;
//Several unrelevant fields here
public Person(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
//Several unrelevant methods here
}
And this is the code i'm currently using to get one of the instances on the list, that is on the main class.
public class Main
{
private List<Person> people = new ArrayList<Person>();
//More unrelevant fields here
public Person getPerson(String name)
{
for (Person p : people)
if (p.getName().equalsIgnoreCase(name))
return p;
return null;
}
//More unrelevant methods here
}
My question is if there's any other way to write this to increase the performance.
Use a Map whose keys are the names and whose values are the people.
HashMap is case sensitive. If you wanted case-insensitive lookups, you could use a TreeMap. My example demonstrates that people with the same name (case insensitively) overwrite each other.
import java.util.Map;
import java.util.TreeMap;
public class SoMain {
Map<String, Person> nameToPersonMap =
new TreeMap<String, Person>(String.CASE_INSENSITIVE_ORDER);
public static void main(String[] args) {
new SoMain().run(args);
}
private void run(String[] args) {
addPerson(new Person("Jim McDonald", 1));
addPerson(new Person("Jim Mcdonald", 2));
addPerson(new Person("John Smith", 3));
System.out.println("Number of people: "
+ nameToPersonMap.entrySet().size());
System.out.println("Jim McDonald id: "
+ getPerson("Jim McDonald").getPersonId());
System.out.println("John Smith id: "
+ getPerson("john smith").getPersonId());
}
private void addPerson(Person p) {
nameToPersonMap.put(p.getName(), p);
}
private Person getPerson(String name) {
return nameToPersonMap.get(name);
}
public static class Person {
private String name;
private int personId;
public Person(String name, int personId) {
this.name = name;
this.personId = personId;
}
public int getPersonId() {
return personId;
}
public String getName() {
return name;
}
}
}
As Eric mentions, you should use a HashMap, the reasoning for this is because you can look up and add data to one very quickly (on average).
Here is a code example of how to use HashMap using Person.name as the key, this assumes that there is never a person with the same name.
public class Main
{
private HashMap<String, Person> people = new HashMap<String, Person>();
public void addPerson(Person person)
{
people.put(person.getName(), person);
}
public Person getPerson(String name)
{
// get returns null when not found
return people.get(name);
}
}
I'm just working through a few things as practice for an exam I have coming up, but one thing I cannot get my head round, is using a variable that belongs to one class, in a different class.
I have a Course class and a Student class. Class course stores all the different courses and what I simply want to be able to do is use the name of the course, in class Student.
Here is my Course class:
public class Course extends Student
{
// instance variables - replace the example below with your own
private Award courseAward;
private String courseCode;
public String courseTitle;
private String courseLeader;
private int courseDuration;
private boolean courseSandwich;
/**
* Constructor for objects of class Course
*/
public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
{
courseCode = code;
courseTitle = title;
courseAward = award;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
}
}
And here is Student:
public class Student
{
// instance variables - replace the example below with your own
private int studentNumber;
private String studentName;
private int studentPhone;
private String studentCourse;
/**
* Constructor for objects of class Student
*/
public Student(int number, String name, int phone)
{
studentNumber = number;
studentName = name;
studentPhone = phone;
studentCourse = courseTitle;
}
}
Am I correct in using 'extends' within Course? Or is this unnecessary?
In my constructor for Student, I am trying to assign 'courseTitle' from class Course, to the variable 'studentCourse'. But I simply cannot figure how to do this!
Thank you in advance for your help, I look forward to hearing from you!
Thanks!
Am I correct in using 'extends' within Course? Or is this unnecessary?
Unfortunately not, if you want to know whether your inheritance is correct or not, replace extends with is-a. A course is a student? The answer is no. Which means your Course should not extend Student
A student can attend a Course, hence the Student class can have a member variable of type Course. You can define a list of courses if your model specifies that (a student can attend several courses).
Here is a sample code:
public class Student{
//....
private Course course;
//...
public void attendCourse(Course course){
this.course = course;
}
public Course getCourse(){
return course;
}
}
Now, you can have the following:
Student bob = new Student(...);
Course course = new Course(...);
bob.attendCourse(course);
I assume a Course is not a Student, so inheritance between those classes is probably a bad idea.
You have to declare them public.
A better way is the keep them private, and code a public getter for that variable. for example:
public Award getCourseAward(){
return this.courseAward;
}
Course should not extend Student. If you want to access the courseTitle field of Course, you need to pass a reference to a Course object to the Student and then do course.CourseTitle.
You cannot access private attributes of a class from another, this is one of the main principles of OOP: encapsulation. You have to provide access method to those attribute, you want to publish outside the class. The common approach is setter/getters - getters only, if you want to have your class immutable. Look here: http://en.wikipedia.org/wiki/Mutator_method#Java_example
It does not make sense to arbitrarily extend classes. Student is not a Course or vice versa, so you cannot extend them like that.
What you need to do is:
create a Course first:
Course aCourse = new Course(..);
create a Student:
Student aStudent = new Student(..);
assign the Course to the Student:
aStudent.setCourse(aCourse.title);
Extending Student with Couse because they are not of the same kind. Extending one class with another happens when specializing a more general (in a sense) one.
The solution would be to pass courseTitle as an argument of the Student constructor
There should be 3 separate objects here, a Course, a Student, and an Enrollment. An enrollment connects a Student to a Course, a Course has many Students, and a Student can enroll in many courses. None of them should extend each other.
First,
You are extending Student class in Course class, which means, student class gets all the coruse class properties. So, the student class does not have the courseTitle property.
Second, yes, it is unnesessary - you need to do the following:
public class Course
{
private Award courseAward;
private String courseCode;
public String courseTitle;
private String courseLeader;
private int courseDuration;
private boolean courseSandwich;
public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
{
courseCode = code;
courseTitle = title;
courseAward = award;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
}
}
public class Student
{
private int studentNumber;
private String studentName;
private int studentPhone;
// This is where you keep the course object associated to student
public Course studentCourse;
public Student(int number, String name, int phone, Course course)
{
studentNumber = number;
studentName = name;
studentPhone = phone;
studentCourse = course;
}
}
Example usage would be something like this:
Course course = new Course("ASD", "TITLE", null, "ME", 50, true);
Student student = new Student(1, "JOHN", "5551234", course);
And then, get the course information you need from student via, i.e.:
student.studentCourse.courseTitle;
Since now student.studentCourse will be a course object with all of its properties.
Cheers,
Maybe you do not need to add the course name to student. What I would do is add Students to some datastructure in Course. This is cleaner and reduces the coupling between Course and Student. This would also allow you to have Students being in more than one course. For example:
public class Course extends Student{
private Award courseAward;
private String courseCode;
public String courseTitle;
private Student courseLeader;//change to a student Object
private int courseDuration;
private boolean courseSandwich;
private Set<Student> students;//have course hold a collection of students
/**
* Constructor for objects of class Course
*/
public Course(String code, String title, Award award, Student leader, int duration, boolean sandwich){
courseCode = code;
courseTitle = title;
courseAward = award;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
this.students=new HashSet<Student>();
}
public boolean addStudent(Student student){
return students.add(student);
}
public Set<Student> getStudents(){
return students;
}
}
As mentioned, stay away from the "extends" for this. In general, you shouldn't use it unless the "is-a" relationship makes sense.
You should probably provide getters for the methods on the Course class:
public class Course {
...
public String getTitle() {
return title;
}
}
And then if the Student class needs that, it would somehow get a hold of the course (which is up to you in your design), and call the getter:
public class Student {
private Set<Course> courses = new HashSet<Course>();
public void attendCourse(Course course) {
courses.add(course);
}
public void printCourses(PrintStream stream) {
for (Course course : courses) {
stream.println(course.getTitle());
}
}
}
Here below find out the solution of your problem and if you want to check below code on your machine then create a file named Test.java and paste the below codes:
package com;
class Course
{
private Award courseAward;
private String courseCode;
public String courseTitle;
private String courseLeader;
private int courseDuration;
private boolean courseSandwich;
public Course(String code, String title, Award award, String leader, int duration, boolean sandwich)
{
courseAward = award;
courseCode = code;
courseTitle = title;
courseLeader = leader;
courseDuration = duration;
courseSandwich = sandwich;
}
public Award getCourseAward() {
return courseAward;
}
public void setCourseAward(Award courseAward) {
this.courseAward = courseAward;
}
public String getCourseCode() {
return courseCode;
}
public void setCourseCode(String courseCode) {
this.courseCode = courseCode;
}
public String getCourseTitle() {
return courseTitle;
}
public void setCourseTitle(String courseTitle) {
this.courseTitle = courseTitle;
}
public String getCourseLeader() {
return courseLeader;
}
public void setCourseLeader(String courseLeader) {
this.courseLeader = courseLeader;
}
public int getCourseDuration() {
return courseDuration;
}
public void setCourseDuration(int courseDuration) {
this.courseDuration = courseDuration;
}
public boolean isCourseSandwich() {
return courseSandwich;
}
public void setCourseSandwich(boolean courseSandwich) {
this.courseSandwich = courseSandwich;
}
}
class Student
{
private int studentNumber;
private String studentName;
private int studentPhone;
private Course studentCourse;
/**
* Constructor for objects of class Student
*/
public Student(int number, String name, int phone, Course course)
{
studentNumber = number;
studentName = name;
studentPhone = phone;
studentCourse = course;
}
public int getStudentNumber() {
return studentNumber;
}
public void setStudentNumber(int studentNumber) {
this.studentNumber = studentNumber;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentPhone() {
return studentPhone;
}
public void setStudentPhone(int studentPhone) {
this.studentPhone = studentPhone;
}
public Course getStudentCourse() {
return studentCourse;
}
public void setStudentCourse(Course studentCourse) {
this.studentCourse = studentCourse;
}
}
class Award{
private long awardId;
private String awardName;
Award(long awardId, String awardName){
this.awardId = awardId;
this.awardName = awardName;
}
public long getAwardId() {
return awardId;
}
public void setAwardId(long awardId) {
this.awardId = awardId;
}
public String getAwardName() {
return awardName;
}
public void setAwardName(String awardName) {
this.awardName = awardName;
}
}
public class Test{
public static void main(String ar[]){
// use your all classes here
}
}