How to store an object in to a variable - java

I am a beginner in JAVA and I could use some help. So I have 3 classes : Client,BankAccount and Test. I need to add into a Client object the details from a BankAccount. This is the code:
public class Client {
private String name;
private String adress;
private BankAccount accounts[];
public Client(String name,String adress,BankAccount accounts){
this.name=name;
this.adress=adress;
this.accounts=accounts;
}
public class BankAccount {
private String numarCont;
private float suma;
public ContBancar(String accNumber,float sum){
this.accNumber=accNumber;
this.sum=sum;
}
public class Test {
public static void main(String[] args) {
Bankaccount b=new Bankaccount("f211s1",200);
Bankaccount b1=new Bankaccount("f23131EUR",5000);
System.out.println(b);
Client c=new Client("John","142VineYard",b);
System.out.println(c);
}
}
A client can have multiple accounts. The problem is that I don't know how can I add the details of object b into object c.

Use a List for your BankAccounts
public class Client {
private String name;
private String adress;
private List<BankAccount> accounts = new ArrayList<BankAccount>();
public Client(String name,String adress,BankAccount account){
this.name=name;
this.adress=adress;
this.accounts.add(account);
}
public void addBankAccount(BBankAccount account){
this.accounts.add(account);
}
}
This way it is a easier to add Accounts.
c.addBankAccount(b);
c.addBankAccount(b1);
Maybe it would help you to take a look at some basic Java tutorials.

It sounds like what you want is inheritance. Inheritance will allow you to use the methods of one class in another class as if it was the same object. The keyword for inheriting in Java is extends used like this:
Public class foo extends foobar

Related

Giving the object to create as parameta in constuctor

sorry for the title I don't know how to say that.
So basically what I want to do is the following:
public class TestClass {
private final String name;
public TestClass(String name) {
this.name = name;
}
public TestClass(TestClass test) {
this = test;
}
public String getName() {
return name;
}
}
So create a class where you can give an object from itself in the constructor
I don't know if that is possible at all.
The problem I have is that I have multiple objects that extend from this class and I want a simple way to pass them to the next class
so when I have 2 classes
TestClass2 extends TestClass
TestClass3 extends TestClass
and I want to create an instance of the testclass3 from the testclass2 one.
they both should have the same name from testcalss
currently, I am doing that like that:
private class TestClass2 extends TestClass{
private final String anotherName;
public TestClass2(String name, String anotherName) {
super(name);
this.anotherName= anotherName;
}
private void createTest3(String whatever) {
new TestClass3(this, whatever);
}
}
private class TestClass3 extends TestClass{
private final String whatever;
public TestClass3(TestClass test, String whatever) {
super(test.getName());
this.whatever = whatever;
}
}
In my case, my base class has not just a name but a lot more values that I then have to submit!
I hope you kinda understand what I want to say. Again sorry I explained that very bad :D
And thank you all thanks in advance for any answers!

Java factory but objects have slightly differrent attributes

I want to program a factory that creates two types of People which are "Employee" and "Entrepreneur". They both share the same basic "Person" attributes but they also implements their unique ones.
The problem is that if i want to return a method or an attribute that is not declared in the "Person" abstract class the program doesn't find it (since obviously I'm generating an object that is type "Person" and not specifically "Employee" or "Entrepreneur" ).
How do i tackle this problem?
This is the Demo class
public class Demo{
public static void main(String[] args){
PersonFactory pf = new PersonFactory();
Person p1 = pf.getPerson("Employee");
p1.presentation();
System.out.println(p1.getComplanyName());
}
}
This is the abstract class
public abstract class Person{
String name;
String surname;
abstract void presentation();
}
Those are the two concrete classes that extend Person
public class Entre extends Person{
int licenseNumber;
#Override
public void presentation(){
System.out.println("hi i'm an Entrepreneur");
}
public int licenseNumber(){
return licenseNumber;
}
}
public class Empl extends Person{
String companyName;
#Override
public void presentation(){
System.out.println("hi i'm an employee");
}
public String getCompanyName(){
return companyName;
}
}
Finally the Factory
public class PersonFactory{
public Person getPerson(String type){
if(type.equalsIgnoreCase("ENTREPRENEUR")){
return new Entre();
}
else if(type.equalsIgnoreCase("Employee")){
return new Empl();
}
return null;
}
}

how should i add an object to a private static ArrayList?

i have Bank class, with a private static ArrayList that stores all the banks. how can i add every new bank created to it?
i'm not allowed to create any new methods or fields, or change any of the method or constructor parameters.
this is my Bank class:
public class Bank {
private static ArrayList<Bank> allBanks=new ArrayList<Bank>();
private String name;
public Bank(String name) {
this.name = name;
}
public String getName() {
return name;
}
and this is my Main class:
public class Main {
public static void main(String[] args) {
new Bank("randomBankName");
}
}
Do it in constructor:
public Bank(String name) {
this.name = name;
allBanks.add(this);
}
WARNING never do it in real project.
You didn't say, that you may not change the visibility of fields, so that would be one way to do this: make the ArrayList public
If you may not do this either, there is a last way, which i'd never do: Reflection.
In most cases, thats really the last way, not recommended!

How can I express object which should be 2 different classes at the same time

Today I had test in OOP and I was given the following task to code:
Imagine you have two classes: Employee (which represents being an employee) and Ninja (which represents being a Ninja). An Employee has both state and behaviour; a Ninja has only behavior. You need to represent an employee who is also a ninja (a common problem in the real world). By creating only one interface and only one class (NinjaEmployee), show how you can do this without having to copy method implementation code from either of the original classes. Test your code in main method
I did not really understand the problem well, but this is the solution I came with (I know it's not what was asked):
I created 4 classes except main. As Employee has state and behaviour I came up with this code:
public class Employee {
private int ID;
private String Name;
private double salary;
public Employee(int ID, String Name, double salary) {
this.ID = ID;
this.Name = Name;
this.salary = salary;
}
public int getID() {
return ID;
}
public void setID(int ID) {
this.ID = ID;
}
public String getName() {
return Name;
}
public void setName(String Name) {
this.Name = Name;
}
public double getSalary() {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public void startWorking() {
System.out.println("Started Working");
}
}
Class ninja has only behaviour:
public class Ninja {
public Ninja(){}
public void moveNinja(){
System.out.println("Ninja moved");
}
}
Class NinjaEmployee:
public class NinjaEmployee extends Employee implements MyInterface {
public NinjaEmployee(int ID, String Name, double salary) {
super(ID, Name, salary);
}
public void moveNinja() {
System.out.println("Ninja Moved");
}
}
Interface which does not make sense in my code:
public interface MyInterface {
public void moveNinja();
public void startWorking();
}
Main class:
public static void main(String[] args){
MyInterface em = new NinjaEmployee(123,"Sandro",1000000);
em.moveNinja();
em.startWorking();
}
My question is following:
1) Specifically/Technically what was asked in test?
2) What would be correct approach/code for given problem?
Nice question.
The key point of the question is:
we should use one interface.
Ninja class should have some methods (not attributes).
So we should try to use these key point.
I provide a class diagram below:
First of all: We have Employee class and implement it like other simple classes. It has some implemented attributes and classes.
Secondly: We have an Interface named Ninja_Interface that have some method declarations about ninja. (moveNinja1 and moveNinja2)
Thirdly: Ninja Class that implemented (or Realized) Nijna_Interface and have some implementation of any method declarations in Ninja_Interface.
Fourthly: the NinjaEmployee class. It inherited from Employee. So it has all Employee's attributes and methods. Also it implements Ninja_Interface. So it should implements all Ninja_Interface methods declarations. On the other hand, NinjaEmployee have an instance of Ninja (notice that Ninja class implements all Ninja_Interface methods). So, In Ninja_Employee class, in implementation of Ninja_Interface methods, we can use Ninja instance methods to call.
For example some parts of NinjaEmployee is like below code:
private Ninja ninja=new Ninja();
public void moveNinja1()
{
ninja.moveNinja1();
}
public void moveNinja2()
{
ninja.moveNinja2();
}
Main question is: why Ninja class should have only some methods?
It is because of Ninja class is just the implementations of Ninja_Interface methods and there no need to have attributes. So instances of Ninja class are the same. So we can declare Ninja attribute in NinjaEmployee as static attribute.
Finally: we can add some attributes of ninja into NinjaEmployee class too.
I don't know correct answer (task is kinda not very strictly defined, there is some unclear moments), but i would do something like this:
public interface IAmNinja {
public void moveNinja();
}
public interface IAmEmployer {
public void startWorking();
}
public class NinjaEmployee implements IAmNinja, IAmEmployer {
private Ninja _ninja;
private Employer _employer;
public NinjaEmployee(int ID, String Name, double salary) {
_employer = new Employer(ID, Name, salary);
_ninja = new Ninja();
}
public void moveNinja() {
_ninja.moveNinja();
}
public void startWorking() {
_employer.startWorking();
}
}
You cant create 1 object of 2 class es
You can extend class so whenever child class is instantiated it calls parent class constructor
Then You can create object of another class in that constructor
Add employees in array and add option to add employee in ninja? 1.yes or 2.no?
if yes , add to ninja..then in main method print names of ninja using for loop one by one

How to call a method in another class in Java?

Currently I have two classes. a classroom class and a School class. I would like to write a method in the School class to call public void setTeacherName(String newTeacherName) from the classroom class.
classroom.java
public class classroom {
private String classRoomName;
private String teacherName;
public void setClassRoomName(String newClassRoomName) {
classRoomName = newClassRoomName;
}
public String returnClassRoomName() {
return classRoomName;
}
public void setTeacherName(String newTeacherName) {
teacherName = newTeacherName;
}
public String returnTeacherName() {
return teacherName;
}
}
School.java
import java.util.ArrayList;
public class School {
private ArrayList<classroom> classrooms;
private String classRoomName;
private String teacherName;
public School() {
classrooms = new ArrayList<classroom>();
}
public void addClassRoom(classroom newClassRoom, String theClassRoomName) {
classrooms.add(newClassRoom);
classRoomName = theClassRoomName;
}
// how to write a method to add a teacher to the classroom by using the
// classroom parameter
// and the teachers name
}
You should capitalize names of your classes. After doing that do this in your school class,
Classroom cls = new Classroom();
cls.setTeacherName(newTeacherName);
Also I'd recommend you use some kind of IDE such as eclipse, which can help you with your code for instance generate getters and setters for you. Ex: right click Source -> Generate getters and setters
Try this :
public void addTeacherToClassRoom(classroom myClassRoom, String TeacherName)
{
myClassRoom.setTeacherName(TeacherName);
}
class A{
public void methodA(){
new B().methodB();
//or
B.methodB1();
}
}
class B{
//instance method
public void methodB(){
}
//static method
public static void methodB1(){
}
}
in School,
public void addTeacherName(classroom classroom, String teacherName) {
classroom.setTeacherName(teacherName);
}
BTW, use Pascal Case for class names. Also, I would suggest a Map<String, classroom> to map a classroom name to a classroom.
Then, if you use my suggestion, this would work
public void addTeacherName(String className, String teacherName) {
classrooms.get(className).setTeacherName(teacherName);
}
Instead of using this in your current class setClassRoomName("aClassName"); you have to use classroom.setClassRoomName("aClassName");
You have to add the class' and at a point like
yourClassNameWhereTheMethodIs.theMethodsName();
I know it's a really late answer but if someone starts learning Java and randomly sees this post he knows what to do.

Categories