I'm supposed to kinda create a student account in java (I'm very new to Java so please don't flame me). Everything is working fine except for when I need to set a Name/degree program (so string I believe). By the way, I'm using BlueJ.
I have tried using the void instead of string but I get the same problem. I also did this before the method starts:
private String studentName;
public String setStudentName (String setStudentName) {
return studentName = setStudentName;
}
I just want to set the Student Name so I can work with it, but if I try running it, I get the following error: "Error: cannot find symbol - variable Robin" Robin is the Name I tried to enter.
Your class and methods should look something like this:
public final class Student {
private String studentName;
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
}
Then, you can use your class like so:
public static void main(String[] args) {
Student student = new Student();
student.setStudentName("Robin");
System.out.println(student.getStudentName());
}
Take a look into the official Java Tutorials on how to write classes.
Just want to sum up all responses above, you have to write this.studentName = studentName instead of studentName = studentName, because in your context you have both method class field and method parameter studentName, so if you write inside your method studentName you work with method parameter. this is link to 'class instance itself' and this.studentNamecalls exactly class field.
One more solution is to rename studentName method param to e.g. newStudentName so it wouldn't be in conflict with class field and afterwords studentName = newStudentName will work as you expects.
Related
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);
}
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());
}
}
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I hope I am asking the right question. This is just out of my curiosity and since I am not an experienced developer, I just to wanted to hear from you guys that what is the good approach while designing a class. Is there any standard approach or either one can be implemented? I just to want to know what is the conventional way of creating a class or what is your way?
Option 1:
public class Student{
private String name;
private String address;
public Student(String name, String address){
this.name = name;
this.address = address;
}
public void addStudent(){
//add name and address to database.
}
}
Option 2:
public class Student{
public void addStudent(String name, String address){
//add name and address to database.
}
public void addAllStudent(List Student){
//loop and add each student to database
}
}
Method call:
//option 1:
Student s = new Student("abc","xyz");
s.addStudent();
//for list,
for(int i=0;i<list.length;i++){
Student s = new Student(list[i].name, list[i].address);
s.addStudent();
}
//option 2:
Student s = new Student();
s.addStudent("abc","xyz");
s.addAllStudent(list);
Option 2 is not good, since both methods dont really have anything to do with the Student object they belong to. You could make those two methods static. Option 1 is the "right" way for a Student class, but the method addStudent() is wrong. You can have a method in your database and call database.addStudent(objStudent).
You could also change the addStudent method in your Student class to addToDatabase(Database db) or even
static void addToDatabase(Student student, Database db)
In the specific case of a List as Database, there is no need for a custom add method at all, because List allready has the add method.
In the most simple case it all boils down to:
List<Student> students = new ArrayList<Student>();
students.add(new Student("Max", "###"));
If you think the second line is too complicated, you can create a static method in Student:
public static void addStudent(String name, String address, List<Student> students)
{
students.add(new Student(name, address);
}
Then you can use it like this:
List<Student> students = new ArrayList<Student>();
Student.addStudent("Max", "###", students);
From personal preference i would not do the latter. It bugs me a little that its not transparent enough in terms of what the method actually does with the list. There is nothing wrong with simply using the add method of the list in the first case.
As you can see there are a lot of opinions on this question, so I go and add another one ;)
Someone commented that there is no "silver bullet" to use when creating new instances of a class. That pretty much hits the bull's eye. There are many ways, straight forward via a constructor, via static methods or wrapped in Factories. And there are even very good arguments to create an instance via reflections.
The same is true for how to save your students to the database. There are many patterns that may be valid. Just make sure you understand how that pattern works and what are the benefits and disadvantages. And just as important, use it consequently throughout your code.
Regarding your code, your option 2 does not make sense if you change to a modeling perspective. Adding students to a student? Unless you don't want to create a human pile of students, you better add students to a course, a class, a school...
Well... first things first... there is a difference between the a Studentand a List<Student>
Normally you would create a class Student
public class Student{
private String name;
private String address;
public Student(String name, String address){
this.name = name;
this.address = address;
}
// and some getter
}
and somewhere else in your code you can use a java List (not in your Student-Class)
List<Student> students = new ArrayList<Student>();
Student peter = new Student("Peter", "somewhere");
Student frank = new Student("Frank", "somewhere else");
students.add(peter);
students.add(frank);
This Code snipped could be in your SubscribeStudentToCourseService or so...
What you want to do is - SingleResponsibility:
Create a class which is responsible for only one thing:
a StudentClass which represents the student as a java model
a course which represents a course (perhaps with a List<Student> field for the students who visit the course
perhaps you write a Service To subscribe Students to a course
It seems you are using the same class to provide a template for a Student, and also to store Students.
Do you really need to store students in the same class? It will lead to some confusing design, where you've got a Student class storing other Student classes which actually represent a student.
Perhaps the functionality for adding a student could be in a separate class, such as a School? Or you just create a generic List of Students wherever you need them. So the addStudent functions could possibly be removed from the class and stored elsewhere.
You can try something like this:
Create a Student bean
public class Student {
private String name;
private String address;
public Student(String name, String address) {
this.name = name;
this.address = address;
}
// generate the getters and setters
}
Create the DAO class
public class StudentDaoIml {
public void addStudent(Student student) {
// do the add student job here
}
public void addAll(List<Student> students) {
// the code goes here
}
public void deleteStudent(Student student) {
}
...
}
At the end you can use it like this:
StudentDaoIml stDao = new StudentDaoIml();
for(int i=0;i<someValue; i++){
Student s = new Student(list[i].name, list[i].address);
stDao.addStudent(s);
}
Here's a good way and some explanation in comments.
public class Student{
private String name;
private String address;
public Student(String name, String address){
this.name = name;
this.address = address;
}
public void save(){
//save this instance to database.
}
public static void saveAll(List<Student> students){
//Either iterate and call save
// or do better batch insert for better performance
}
}
As far as naming a method is concerned, class methods are named in terms of their behaviour. Think of it like telling an instance of student to 'go and save yourself to DB'. There could be one more method like 'go and update yourself in DB'.
When you are dealing with a list, the list itself should not be part of the Student class. Keep the list somewhere else. However, the Student class could have a static method which takes a list of students and saves them in one shot.
For example, the students could be in a class in a school. Then
Student.saveAll(class5A.getStudents());
Create a few and save them:
List<Student> students = new ArrayList<>();
for(int i=0;i<10;i++){
Student s = new Student("Student" + i, "Student address " + i);
students.add(s);
}
Student.saveAll(students);
Going one step further, Student class should probably not deal with saving students in bulk. So, let's relieve it of that duty and let the BatchOfClass take care of that.
public class Student{
private String name;
private String address;
public Student(String name, String address){
this.name = name;
this.address = address;
}
public void save(){
//save this instance to database.
}
}
public class BatchOfClass{ //Students who are in grade 6 in 2016
private String className;
private String batchName;
private List<Student> students;
public BatchOfClass(...){
}
public void save(boolean saveStudents){
//save this instance to database.
//This would also save the students to DB if saveStudents==true
}
}
I have a method:
public User(String name) {
//create a user with the appropriate name}
I want to create something where if someone types in
User (bob);
an instance of the user class with the name "bob" will appear.
I tried to use this code:
public User(String name) {
User name = new User();
but I am getting errors that state the the constructor User(); is undefined and also that there is a duplicate local variable name. I know this is a basic question, but I can't seem to figure it out and any help would be appreciated.
The first bit of code you have is a constructor, not a method. It exists to tell Java how to create your class when using the new keyword.
You likely want to do this:
public class User{
private String name;
public User(String n){
name = n; // When creating my User, give him this name
}
public String getName(){
return name;
}
}
That defines your User class. Now you can create one anywhere
public class MyApplication{
public static void main(String[] args){
User user = new User("Tom");
System.out.println(user.getName());
}
}
Not sure if I followed what you were asking for... but this might be it. As some of the comments mention, I would highly recommend picking up a good beginner Java programming book to better grasp the basics of constructors.
public User(String inName) {
name = inName;
}
//...
new User("Bob");
Use:
User name = new User("yourname");
Then add a constructor with a string parameter.
A small segment of testing code as follows:
class Teacher {
private String title;
String name = "A";
int age = 20;
Teacher (String title) {
//System.out.println(name);
this(name,age,title);
}
Teacher (String name, int age, String title) {
System.out.println("OK");
}
}
public class Test {
public static void main (String[] args) {
Teacher teacher1 = new Teacher("John");
Teacher teacher2 = new Teacher("Mike",25,"TA");
}
}
As above, I annotated System.out.println(name); After compiling, there was an error:Can't reference name(age) before the superclass constructor has been called. However, I annotated this(name,age,title);, which meant I only used System.out.println(name);. And the error was gone. Thus, I think the name and age has been initialized and get the value A,20. That is to say, this(name,age,title) is actually this("a",20,"John") I don't know the principle. Need your help.
this/super constructor call has to be the first statement when you chain constructor call. See this for details.
The principle is,
If present, the invocation of another constructor must be the first
line in the constructor.
Reference : JavaDoc
Using this keyword you are invoking other constructor.
When you comment out the first statement, the constructor call becomes first line which is legal.
Java Documentation says that
If present, the invocation of another constructor must be the first line in the constructor.
You can't access the fields name and age when calling this(). The fields have not been initialized yet. If you want name to be "A" by default and age to be 20, enter the values directly as parameters to this().
The following class will compile:
class Teacher {
private String title;
String name;
int age;
Teacher (String title) {
this("A",20,title);
}
Teacher (String name, int age, String title) {
this.name = name;
this.age = age;
System.out.println("OK");
}
}