I am trying to set specific values of objects in an Array with a method.
public class BankAccount
{
private String name;
//constructor
public BankAccount(String firstName, String LastName)
{
name = firstName + " " + lastName;
}
public String getName()
{
return name;
}
Above is my BankAccount class, and I have another class named BankAccountList:
public class BankAccountList {
public static void main(String args[]){
BankAccount bankAccount[] = new BankAccount[2];
bankAccount[1] = giveName("MR", "Travis");
}
public static void giveName (String firstName, lastName){
}
}
How do I set the object name in BankAccount[1] to "Mr Travis" with the following giveName() method? I don't know what to put in giveName with the given parameter. Any tips would be much appreciated.
Your giveName method should return the type BankAccount:
public static BankAccount giveName (String firstName, String lastName){
return new BankAccount(firstName, lastName);
}
Edit:
Simply declaring new BankAccount[] does not populate any entries in the array (which you might expect based on experiences with other languages). The array will initially be empty, and there are multiple ways to populate it:
Inside a loop you could:
Call the BankAccount constructor directly
Delegate to another method that returns a new .collect(Collectors.toSet()) (as the example above does)
This choice, like most programming decisions, is mostly personal preference. For a simple DTO with 2 string fields, delegating to another method might be overkill.
For a more complex DTO that requires validation, delegating to another method helps encapsulate that validation logic in a single place that is easily testable.
There are a few things worth mentioning here.
First of all, it seems like you do not have a complete understanding of the difference between static and dynamic. It is understandable, as I even now would have a hard time explaining it easily, even though I understand how it works. Your BankAccountList class has a main method, started from a static standard main method. your bankAccount array is defined within this main method, meaning it does not exist in the whole class, only inside the running main method.
Then you want to give name to a bank account in the list. Here you have created another static method, which knows nothing about what is inside your main method, and it does not contain any object which the parameters can be given to. In other words the empty function you have now, can't set any parameters to a bank account, because no bank account exists within the method.
I would recommend making the giveName method dynamic (which means just removing the static keyword), and move the method to the BankAccount class. Then you will efficiently have both a get and set method for name, which are dynamic, meaning it is valid per object instance of the class. After that, it is possible to first refer to an object in the array, and directly call the giveName() method on that particular object, which will set the name:
public class BankAccount
{
private String name;
//constructor
public BankAccount(String firstName, String LastName)
{
name = firstName + " " + lastName;
}
public String getName()
{
return name;
}
public void giveName (String firstName, String lastName){
name = firstName + " " + lastName;
}
and:
public class BankAccountList {
public static void main(String args[]){
BankAccount bankAccount[] = new BankAccount[2];
bankAccount[1].giveName("MR", "Travis");
}
}
UPDATE:
I noticed now another thing. The line where you create the array:
BankAccount bankAccount[] = new BankAccount[2];
This does not create a populated array, it creates an empty array. in other words, you have not created a list with bank accounts, you have created a list which can hold bank accounts. You will have to create a bank account first, before being able to give it a name.
BankAccount bankAccount[] = new BankAccount[2];
bankAccount[1] = new BankAccount("MR", "Travis");
Now, your constructor already has parameters for giving an account a name, when created. So now you don't really need the giveName method. Unless you want to change it later:
bankAccount[1].giveName("MRS", "Davis");
You don't really need to use giveName method, you could just do it like this:
bankAccount[1] = new BankAccount("MR", "Travis");
But, if you really need to do it using a giveName method, you could do it like this:
// change signature to return `BankAccount` object
public static BankAccount giveName (String firstName, String lastName){
return new BankAccount(firstName, lastName);
}
and call it like this: bankAccount[1] = giveName("MR", "Travis");
If you need giveName to have void as return type, then you need to pass the array in order to add the BankAccount inside the method and the position were it will be added. Like this:
// change in order to signature receive an array of `BankAccount`s and the position where it will be added
public static void giveName (String firstName, String lastName, BankAccount[] bankAccounts, int position) {
bankAccounts[position] = new BankAccount(firstName, lastName);
}
and then call it like this: giveName("MR", "Travis", bankAccount, 1);
Additional notes:
Remember array positions start at index 0, not 1, so you might want to consider adding bank account from 0, not 1, like this:
This is the case if giveName is in the BankAccountList class. Otherwise, go for KjetilNordin's answer.
bankAccount[0] = giveName("MR", "Travis");
You defined an array that will hold BankAccount objects, so to add elements into it with the function giveName() you need to modify that function as following :
public class BankAccountList {
public static void main(String args[]){
BankAccount bankAccount[] = new BankAccount[2];
bankAccount[1] = giveName("MR", "Travis");
}
public static BankAccount giveName (String p_firstName,String p_lastName){
return new BankAccount(p_firstName, p_lastName)
}
}
You need set methods!
Add this to class BankAccount:
public void setName(String firstName, String lastName) {
this.name = firstName + " " + lastName;
}
so you should call setName instead of giveName. Like this:
bankAccount[1].setName(String firstName, String lastName)
Another thing, I suggest you use the set method in the constructor of your object:
//constructor
public BankAccount(String firstName, String LastName)
{
setName(String firstName, String lastName);
}
Related
I am new to Java. I have a problem to solve, but I don't quite understand how constructors work. I understand how to create a superclass and a subclass but I don't understand the constuctors within them (or how they actually work - I have done rediculous amounts of research on constructors, but it's just not making much sense).
I am trying to write a program that creates a superclass called Employees. This Employee class has instance variables employeeId (which is an integer) and employeeName (which is a String).
The subclass is called Manager. The Manager subclass has an instance variable called employeeTitle (which is a String). It also has a method with the name of managerDetails(). ManagerDetails() is supposed to display the employeeId, employeeName, and the employeeTitle.
This is what I have so far:
package tryingoutjava;
public class TryingOutJava {
class Employee {
int employeeId;
String employeeName;
void Employee() {
}
}
class Manager extends Employee {
String employeeTitle;
void managerDetails() {
}
}
public static void main(String[] args) {
}
}
I am very confused on how to set up the constructors for the superclass and the subclass, or even what a constructor really looks like. I've seen examples all over the internet, but no one actually highlights the actual part that is the constructor, or how everything is linked visually, which is what helps me learn.
I guess I'm also having issues with understanding how to set up a method that calls on an object. If anyone has the time to help, it would greatly be appreciated. Thanks!
I guess you want something like this. Be noted, that it is a good idea to separate classes one-per-file in this case, as they are separate entities here. It is a good idea to limit data access to entity fields, as such using encapsulation.
Employee.java:
package tryingoutjava;
public class Employee {
// Protected access because we want it in Manager
protected int employeeId;
protected String employeeName;
public Employee(int employeeId, String employeeName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
Manager.java:
package tryingoutjava;
public class Manager extends Employee {
private String employeeTitle;
public Manager(String employeeTitle, int employeeId, String employeeName) {
// Use super to invoke Employee constructor
super(employeeId, employeeName);
this.employeeTitle = employeeTitle;
}
// Just create a simple string describing manager
#Override
public String toString() {
return "Manager{" +
"employeeTitle='" + employeeTitle +
"employeeId=" + employeeId +
", employeeName='" + employeeName + '\'' +
'}';
}
}
Application.java:
package tryingoutjava;
public class Application {
// Example of construction plus printing of Manager data
public static void main(String[] args) {
Employee davie = new Employee(1, "Dave The Cable Guy");
Manager tom = new Manager("CFO", 2, "Tomas");
System.out.println(tom.toString());
}
}
Constructors (most often than not) just delegate construction of parent through super invocation. While there are other techniques, like Builder pattern, this is the most basic and understandable approach. There are several other ways to do this, but this should get you started, hope it helps!
Purpose of Constructor
constructor is a method like other method but it is called when instantiate (or create a object from your class) for initialize your object for first use or later use. for example a class like Student must created (instantiated) when we give it name and family name for example. Without them, create a Student is not good because maybe we forget to give it proper name and use it incorrectly. constructor forces us to provide minimum things needed for instantiating objects from classes.
Constructor implementation in inheritance
About inheritance, it is different. When you want to create a Student which is a Human (extends Human) you must first create Human inside your Student and set special feature for your Student like ID which is not for Human (Human has name and etc). so when you create a Student with constructor, the super constructor (for Human) is called too.
What do we do in constructor
as I mentioned, we provide default value for our properties which must set them before creating and using object. (for using them properly) every subclass call super class constructor implicitly with super() but if super class doesn't have any default constructor (constructor with no argument) you must explicitly say super(...) at the first lien of subclass constructor (otherwise compile error)
What is the program steps when using constructor (Advanced)
super class static constructor and static variable (read by self if you want to know more about things I say here)
subclass class static constructor and static variable
super class variable and block constructor
super class constructors
sub class variable and block constructor
sub class constructors
I only mentioned 4 & 6.
I try to explain completely. My English is not good. I'm sorry.
If you know how a method works, then you know how a constructor works. The constructor is simply a special method that allows you to execute some code before the object is created.
Person p = new Person("Bob", 25); // Calls constructor Person(String name, int age)
Then in the constructor you can do things like assign initial values to any instance variables.
private String name;
private int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
If the class is a subclass you need to call a constructor of the parent class before the object is created unless the parent class has a constructor with no parameter in which case java can call it for you if you don't specify anything. Here Worker extends Person.
private String occupation;
public Worker(String name, int age, String occupation) {
super(name, age) // Calls constructor Person(String name, int age)
this.occupation = occupation;
}
I guess you can achieve what you want in a single file via the code snippet below:
You can copy paste it in your code and it should work.
You can see how the constructor of parent class is being called by the help of super() and also the methods. Here I have used methods like getEmployeeTitle() which should help you get an overview on how to write methods. I have also overridden the toString() method so that you can understand how to override Object class' useful methods like toString().
Note : Although I have created all the classes in one code snippet for the sake of simplicity , but it is highly recommended that you create a separate file for each of these classes.
class Employee {
int employeeId;
String employeeName;
Employee(int employeeId, String employeeName) {
this.employeeId = employeeId;
this.employeeName = employeeName;
}
}
class Manager extends Employee {
private String employeeTitle;
Manager(int employeeId, String employeeName, String employeeTitle) {
super(employeeId, employeeName);
this.employeeTitle = employeeTitle;
}
public String getEmployeeTitle() {
return employeeTitle;
}
#Override
public String toString() {
return ("employeeId: " + employeeId + ", employeeName: " + employeeName + ", employeeTitle" + employeeTitle);
}
}
public class TryingOutJava {
public static void main(String[] args) {
Manager manager = new Manager(007, "John Doe", " Sr. Manager");
System.out.println(manager);
System.out.println(manager.getEmployeeTitle());
}
}
why the final names printed were the same, if this.name = name is instead, the name would be changed.
another question is in class Name public name(){} was created for? whether just use the next line is ok.
class Name
{
private String firstName;
private String lastName;
public Name() {}
public Name(String firstName, String lastName)
{
this.firstName = firstName;
this.lastName = lastName;
}
public void setFirstName(String firstName)
{
this.firstName = firstName;
}
public String getFirstName()
{
return this.firstName;
}
public void setLastName(String lastName)
{
this.lastName = lastName;
}
public String getLastName()
{
return this.lastName;
}
}
public class Person
{
private final Name name;
public Person(Name name)
{
this.name = new Name(name.getFirstName(), name.getLastName());
}
public Name getName()
{
return new Name(name.getFirstName(), name.getLastName());
}
public static void main(String[] args)
{
Name n =new Name("wukong", "sun");
Person p= new Person(n);
System.out.println(p.getName().getFirstName() + p.getName().getLastName());
n.setFirstName("bajie");
System.out.println(p.getName().getFirstName() + p.getName().getLastName());
}
}
Ok so you are mixing up all objects and references over here. First of all please change your getName() function to :-
public Name getName()
{
return this.name;
}
This will return the current name object associated with the person class and not create a new instance of name like you are doin when you return new Name(...).
And second thing changing values of n (name object ) will not affect the person object p that contains a different instance of name object.
for changing firstName value of your p object replace this
n.setFirstName("bajie");
with this:-
p.getName().setFirstName("bajie");
Edit:- I just saw that your Name field is set as final hence it can be only instantiated and assigned value once in the constructor, after that it cannot change (the reference) although you can reassign p.getName().getFirstName() (Since the object is changing and not the reference).
And for the second question it is a default constructor i.e a no-argument constructor automatically generated unless you define another constructor (Which in your case you have defined)
why the final names printed were the same
you will find answer in Person constructor, this.name = new Name(name.getFirstName(), name.getLastName()); you are not assigning name to person, but you create new objects with it fields. Hence this statement n.setFirstName("bajie"); is not affecting your p
if "this.name = name" is instead, the name would be changed.
try it
is in class Name "public name(){}" was created for? wether just use the next line is ok.
some of frameworks require class to have no-arg construcor. as you defined own constructor you are loosing default no-arg constructor. this line creates one for you
Note about final
private final Name name;
The final modifier indicates that the reference to the Name object pointed by the field name cannot be changed once it is assigned in a constructor or init block. This does not mean that the object pointed by this reference cannot be changed.
Note: Between your field declaration and its first initialization, it is in a "blank" state, waiting for init.
if "this.name = name" is instead, the name would be changed
Comparison
this.name = new Name(name.getFirstName(), name.getLastName());
This piece of code creates a new Name object and initialize your field with a reference to that new object. The created object is initialized with the same content as the argument name. If you later call setFirstName("bajie"); on the name you passed as argument here, it won't change the field's content (because it's another object).
this.name = name;
This piece of code assigns the parameter name's reference to the this.name field. If you later call setFirstName("bajie"); on the name you passed as argument here, it will change the field's content, because it is the same object. It won't change the reference held by the field though.
About the no-arg constructor
another question is in class Name "public name(){}" was created for?
The empty no-arg constructor is the "default" constructor.
However, if you declare another constructor (which is the case here with the second constructor public Name(String firstName, String lastName)), then the default constructor does not exist anymore.
If you want to be able to instantiate a Name without args, you need to redeclare the no-arg constructor.
I am very new to Java. I know the basic concepts of constructors. I know that, if we don't create any constructor also compiler will create default constructor.
I have created a program to check how this toString() method is usable,
public class Vehicle{
int rollNo;
String name;
int age;
public Vehicle(int rollNo, String name, int age){
this.rollNo=rollNo;
this.name=name;
this.age=age;
}
public String toString(){
return rollNo+""+name+""+age;
}
public static void main(String[] args){
Vehicle v=new Vehicle(100, "XXX", 23);
Vehicle v2=new Vehicle(101, "XXXS", 24);
System.out.println(v);
System.out.println(v2);
}
}
And, I am getting output as :
100XXX23
101XXXS24
But, my doubt is why are we creating constructor and passing same variables as arguments to that?
Why can't we assign the values to variables like this and can't we get values without constructor?
public class Vehicle{
int rollNo=100;
String name="XXX";
int age=23;
// public Vehicle(int rollNo, String name, int age){
// this.rollNo=rollNo;
// this.name=name;
// this.age=age;
// }
//
public static void main(String[] args){
// Vehicle v=new Vehicle(100, "XXX", 23);
// Vehicle v2=new Vehicle(101, "XXXS", 24);
Vehicle v=new Vehicle(rollno,name,age);
// Vehicle v2=new Vehicle();
System.out.println(v);
// System.out.println(v2);
}
public String toString(){
return rollNo+""+name+""+age;
}
}
Firstly, it is possible to set the values of attributes or properties without a defined constructor in the class definition. This can be done through the use of setters on the attributes/properties within a Java class. So for example:
public class Vehicle{
int rollNo;
String name;
int age;
// Note no constructor, so the default no-arg constructor can be used.
// Now the setters
public void setRollNo(int anInt) {
this.rollNo = anInt;
}
public String setName(String aName) {
this.name = aName;
}
public void setAge(int anAge) {
this.age = anAge;
}
public static void main(String[] args){
Vehicle v=new Vehicle(); // note no-arg constructor being used.
v.setRollNo(3);
v.setName("Hello");
v.setAge(12);
System.out.println(v);
}
}
The use of setters is far better as you adhere to an important OOP principle; that of encapsulation, which in Java and Software is quite critical.
Please have a look at the following Java Tutorial from Oracle that goes through the use of getters and setters and the use of constructors.
The main method is declared static, which means that it doesn't belong to any particular copy of your class. If you want to create copies of the class to use for whatever purpose, you use new, which causes the constructor to build a copy for you, and in your case set the appropriate variables (which belong to particular copies of the class, like the copies that you're holding in the v and v2 variables).
The fact that the main method is part of the same class is essentially irrelevant; main could be attached to any class, even an otherwise empty one.
The reason why you have to use Constructor having arguments is that created instance is immutable objects which means that whose state cannot be modified after it is created. In other words object does not have setter it only has getter methods.
In java platform GC is the main part of JVM, and immutable objects makes GS less work to clean the unusable objects in heap memory.
Pls refer to link http://c2.com/cgi/wiki?ImmutableObjectsAndGarbageCollection
The default constructor from the compiler will be the following.
public Vehicle()
If you don't define
public Vehicle(int rollNo, String name, int age)
then it won't exist and you can't use it.
Java does not create default constructors with arguments.
In school we have to make a program, which is that you type in personal information, such as namn, age and so on. And you have one button where you save information and one where you type out.
I save this information like this:
Person.name = Name.getText();
Person.age = age.getText();
Person.sex = sex.getText();
And then i have a method. Which takes this information and saves it. Because there is only one button to save information. Can you make new mothods for every new person you save? Should you do it in a loop. That loops out new methods everytime you press? And how.
Thx
You do not need to 'make new methods' each time you want to save the Person data. The point is to create a method which is dynamic, that means you have to have access to the Person class/data and just do as you defined: person.setName(name.getText());
You dont need a new method everytime you save, you need a new Person object. The method that gets called when save is pressed should accept Person as a parameter. So save is pressed it creates a new Person object and populates it like u already do, Person.name = Name.getText();, Person.age = age.getText(); and so on. That populated Person object is then passed to a method which has all the code to save it.
You do not need to make new method every time, what you need to do is just make a class named Person and define its attributes as Name, Age and Sex and make methods that access this variables and sets this variables, as I've shown below:
class Person{
String Name="";
String Age="";
String Sex="";
public String getName(){
return Name;
}
public String setName(String Name){
this.Name=Name;
}
public String getAge(){
return Age;
}
public String setAge(String Age){
this.Age=Age;
}
public String getSex(){
return Name;
}
public String setName(String Sex){
this.Sex=Sex;
}
}
You can access this methods and variables by just making object of this Person class as:
Class UsePerson{
public static void main(String ar[]){
Person p=new Person();
p.setName("ABC"); //Here You set the Name of the person
String name=p.getName(); //Here you'll get the name of Person
}
}
Basically I have to write a simple contact manager, and store objects in array list.
What frustrates me is that I have newContact method, which when called creates new instance of Contact, and stores it in ArrayList. The problem is that every time I call that method, all other objets in the list gets overwritten.
import java.util.ArrayList;
public class ContactManager {
public static ArrayList<Contact> contactList = new ArrayList<Contact>();
public static Contact[]c = {};
public static void main(String[]args){
newContact();
newContact();
System.out.println(contactList.get(1).getName());
System.out.println(contactList.get(0).getName());
}
public static void newContact(){
Contact c = new Contact();
contactList.add(c);
}
}
In Contact class constructore there is code that initializes the object's properties using Scanner class.
If in first call I Enter "John" and in second function call I enter "Peter", the above code will print out:
Peter
Peter.
Why doesn't it prints out John Peter?
Only thing I can think of is that maybe Java stores only reference to object in arraylist, and that unlike variables objects don't get destroyed after function executes..
Any ways around this?
I hope this explains what I am trying to achieve.
PS. I know people hate people that as homework questions. But I am doing this as an extra, in order to learn new stuff. Original assignment barely asks to instantiate 5 objects and store them in ArrayList. And I have that done, now I am just trying to see if I could come up with more dynamic solution.
Contact class code:
import java.util.Scanner;
public class Contact{
private static String name, number;
//constructor will ask to enter contact details
public Contact(){
Scanner in = new Scanner(System.in);
System.out.println("Enter name:");
name = in.next();
System.out.println("Enter number:");
number = in.next();
}
//getters and setters
public static String getName(){
return name;
}
public static String getNumber(){
return number;
}
public static void setName(String newName){
name = newName;
}
public static void setNumber(String newNumber){
number = newNumber;
}
}
It's because the members in the Contact class are static. That means that all Contact instances share the same name and number. You should make them instance members so that each time you do new Contact you get a new copy of these variables.