New to OOP, manage variables in classes [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
So. I got a mission from my teacher to make a program that manages different students. The program will hold the name, education, information and points.
You will have the option to:
Add new students
Change education and information
Manage points
Making new students is not a problem, but managing education, info and points for specific students is the hard part, that's where I need your help. My main.java does not contain anything for now.
Student.java
package student;
public class Student {
String namn;
String program;
String info;
int points;
public void managePoints(){
}
public void changeProgram(){
}
public void changeInfo(){
}
}
Main.java
package student;
public class main {
public static void main(String[] args) {
}
}

According to the comments, I guess the three methods in your class are supposed to change the points, program and info of the student to a desired value. In Java, we call these setters.
You should rename your methods to setPoints, setProgram and setInfo. It's a pattern, you know.
Next, how are you going to know the "desired" value of those fields? You might say, I get them from the text boxes in the methods. But a better approach would be to get the values from another method and pass the value to the setters as a parameter.
To add a parameter to your methods, add a variable-like thingy in the brackets of the method declaration:
public void setPoints (int p)
And for the setInfo
public void setInfo (String i)
And so on.
In the method bodies, you set the fields to the parameters. E.g. In the setInfo method you write
info = i;
I think you can figure out the others.
Now how do you use these methods? For instance, suppose you have a student variable called student. And you got the info of him/her and stored it in a string variable called studentInfo. You can set the student variable's info to studentInfo by
student.setInfo (studentInfo);
Or if you don't want to use a variable, you can just use a string literal.
student.setInfo("this is my info. Blah blah blah");

I don't exactly know what do you want to actually do but your Student class (if I think correctly what you will need) should look more like this:
public class Student {
private String name; // private because you don't want anyone to interact with the variable too much.
private String program;
private String info;
private int points;
public Student( String name, String program, String info, int points ) { // contructor with variables to initialize. You can remove some of the variables if you do not consider they should be here.
this.name = name;
this.program = program;
this.info = info;
this.points = points;
// without `this` you would change parameter's value to itself which isn't what you want.
}
public String getName( ) { // getter because I guess you would like to know students name
return name;
}
public int getPoints( ) {
return points;
}
public void addPoints( int points ) { // setter so you can modify points
this.points += points;
}
public String getProgram( ) { // same as getName
return program;
}
public void setProgram( String program ) {
this.program = program;
}
public String getInfo( ) {
return info;
}
public void setInfo( String info ) {
this.info = info;
}
}
But how to use these methods? You use them as the example below shows
Student s1 = new Student("Abc Xyz", "IT", "Some informations", 12);
Student s2 = new Student("Cba Zyx", "Some other program", "Some more informations, 0);
s2.setInfo( s1.getInfo( ) );
s1.setPoints(1234);
s2.setProgram("Axbzcy");
Getter is a method which returns (most likely) private variable's value.
Setter is a method which sets private variable's value to another value which is passed as a parameter to the method.

Final code:
package student;
// The student class definition
public class Student {
private String name;
private String address;
private String info;
private String kurs;
private int points;
// Constructor
public Student(String name, String address, String info, String kurs, int points) {
this.name = name;
this.address = address;
this.points = points;
this.kurs = kurs;
this.info = info;
}
// Public getter for private variable name
public String getName() {
return name;
}
// Public getter for private variable address
public String getAddress() {
return address;
}
public String getInfo() {
return info;
}
public int getPoints() {
return points;
}
// Public setter for private variable address
public void setAddress(String address) {
this.address = address;
}
public void setPoints(int points){
this.points = points;
}
public void setInfo(String info){
this.info = info;
}
public void setKurs(String kurs){
this.kurs = kurs;
}
// Describe itself
public String toString() {
return name + ", Adress: " + address + ", Info: " + info + ", Kurs: " + kurs + ", Poäng: " + points +" ";
}
}
Main
package student;
// A test driver program for the Student class
public class main {
public static void main(String[] args) {
Student ArHa = new Student("A H", "Jysgaan 61", "ADHD", "Teknik", 5);
ArHa.setPoints(10);
ArHa.setKurs("TEINF");
System.out.println(ArHa);
Student DaSk = new Student("Dael Sklbr", "Fegea 65", "Svart", "Teknik", 5);
DaSk.setInfo("Riktigt svart");
System.out.println(DaSk);
Student FaMe = new Student("Falafel Medusa", "Fågel 123", "Maten", "Kock", 123);
System.out.println(FaMe);
}
}
Thank you everyone for the help.

Related

Using Eclipse, trying to get a program to work

I am currently learning Java with eclipse for my computer science course, and I need some assistance trying to figure out how to fix the error that is currently showing.
package sec4Les2;
public class RoseDS4L2Person {
//creating the variables
public String name = "Uma Thurman";
public int Age = 0;
//constructor
public RoseDS4L2Person()
{
}
public String getname()
{
//will return first name
return name;
}
public int getAge()
{
//will return age
return Age;
}
public void setAge(int Age)
{
//will set age to int
this.Age = Age;
}
}
And here is the running code:
package sec4Les2;
public class RoseDS4L2ManagingPeople {
public static void main(String[] args) {
//runs information in first class file
RoseDS4L2Person p1 = new RoseDS4L2Person("Arial", 37);
RoseDS4L2Person p2 = new RoseDS4L2Person ("Joseph", 15);
if(p1.getAge()==p2.getAge())
{
System.out.println(p1.getname()+" is the same age as "+p2.getname());
}
else
{
System.out.println(p1.getname()+" is NOT the same age as "+p2.getname());
}
}
}
It says there are no errors on the first one, but the second one has errors on the p1/p2 lines. How can I fix this error? thank you!
You should have a constructor for RoseDS4L2Person accepting a string and a number, like so:
public RoseDS4L2Person(String name, int age)
{
this.name = name;
this.Age = age;
}
This will allow you to create an instance of the class passing a name and an age as parameters.
You need to add this code to your class. Basically, a constructor was missing in your class. Also note that by convention, member variables start in lowercase. So your Age should really be age.
Another thing is, you have kept name as constant. Probably you want to remove "Uma Thurman". If you want to keep that as default name for all objects where name is not specified at initialization time, you would want to add that in the constructor. *
public class RoseDS4L2Person
{
// other lines ....
RoseDS4L2Person(String name, int age) {
this.Age = age;
this.name = name;
}
}
*
Something like this:
public class RoseDS4L2Person
{
private static final String UMA_THURMAN = "Uma Thurman";
// other lines ....
RoseDS4L2Person( int age) {
this.Age = age;
this.name = UMA_THURMAN;
}
}
The error is popping up because you have created objects with a non-existing constructor.Making objects with the default constructor or creating a constructor
which can accept the arguments you pass should do the trick.
Happy Coding

What's the importance in using the set method when the attributes have already been defined in the Used Defined Constructor? [duplicate]

This question already has answers here:
Setter methods or constructors
(10 answers)
Why use getters and setters/accessors?
(37 answers)
Closed 6 years ago.
In the below code I've already declared that room = r; subject = s; and time = t; in the user defined constructor, so why is it necessary to do so again in set methods, my lecturer specifically asked that we add set methods for the room subject and time but it's redundant code as when I comment it out it still works. Do you only need to include set methods when there is no used defined constructor? What could be the advantage of having them set methods there?
class LectureTest{
public static void main (String [] args){
Lecture l1 = new Lecture(140, "Comp", 5);
l1.display();
Lecture l2 = new Lecture(280, "Sports", 3);
l2.display();
Lecture l3 = new Lecture(101, "Business", 5);
l3.display();
Lecture l4 = new Lecture(360, "Shooting", 4);
l4.display();
Lecture l5 = new Lecture();
l5.display();
}
}//end of LectureTest
class Lecture{
private int room;
private String subject;
private int time;
Lecture(int r, String s, int t){
room = r;
subject = s;
time = t;
}
Lecture(){}
public void setroomNumber(int r){
room = r;
}
public void setSubject(String s){
subject = s;
}
public void setTime(int t){
time = t;
}
public int getroomNumber(){
return room;
}
public String getSubject(){
return subject;
}
public int getTime(){
return time;
}
public void display(){
System.out.printf("\n" + "Room Number: " + getroomNumber() + "\n" + "Subject: " + getSubject() + "\n" + "Time " + getTime() + "\n");
}
}
The constructor "initializes" your values.
Let's say you have...
public class Person {
public String name;
public int age;
public Person (String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public void setAge(int age) {
this.age = age;
}
public String toString() {
String str;
str = "My name is "+name+" and I am "+age+" years old!";
return str;
}
}//End of Person
public class Main {
public static void main(String [] args) {
Person person = new Person("Bob", 15);
System.out.println(person.toString());
System.out.println("Switching my name...");
person.setName("Joe");
System.out.println(person.toString());
}
}//End of main
You see the difference? You should use the constructor if you want to create a new instance of the object. This way, you can set all the fields of the object at once and not need to call 490832490 setters (in this case, one for name and one for age...). You then can use the setter approach when you want to change the value of a field, PRIOR TO the object been created.
I DID ALL THIS ON THIS FORUM SO I MIGHT HAVE SYNTAX ERRORS SO CAREFUL...DIDN'T USE AN IDE IF YOU WANT TO TEST IT
The set methods make your object mutable. If you don't have the set methods and your variables are private then the Object will be immutable. You won't be able to change the values after it is constructed...If the values need to change you would have to create a new Object.
"Setters" allow you to modify private attributes of your object after instantiating. For example:
Lecture l1 = new Lecture(140, "Comp", 5);
//Since "room" is private you can't write l1.room = 4
//and have to use the setter method instead:
l1.setroomNumber(4);
l1.display();
They are also very useful if you want to do something if an attribute changes.
Let's assume you are using Observers, then you could call notifyObservers() or setChanged() in your setter method and never have to worry about these methods not getting called if your attribute changes.

Java - Using an object inside an object

I am working on a project ( I had a problem yesterday and so many people helped me!) so I decided to ask for help again.
My code has 3 classes. ProjectMain,Students,Classroom. I created an array of Classroom objects. Right now I have 3 Classroom objects. But I have to assign student objects to these Classroom objects. For example : classarray[0] is an object from Classroom class and studentobject.get(0) , studentobject.get(1) ... will be students objects inside classarray[0] object. But I have failed on this while coding. Here are my classes :
public class Classroom
{
private String classname;
private String word[] = null;
protected ArrayList<Students> studentobject = new ArrayList<Students>(10);
public String[] getWord()
{
return word;
}
public void setWord(String[] word)
{
this.word = word;
}
public ArrayList<Students> getStudentobject()
{
return studentobject;
}
public void setStudentobject(ArrayList<Students> studentobject)
{
this.studentobject = studentobject;
}
public String getClassname()
{
return classname;
}
public void setClassname(String classname)
{
this.classname = classname;
}
public void classroomreader(String filename)
{
// This method gets the name of Classroom
File text = new File("C:/Users/Lab/Desktop/classlists/" + filename
+ ".txt");
Scanner scan;
try
{
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t");
line = scan.nextLine();
word = line.split("\t");
} catch (FileNotFoundException e1)
{
e1.printStackTrace();
}
}
}
This is my student class :
public class Students extends Classroom
{
private String name,id;
private int age;
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getId()
{
return id;
}
public void setId(String id)
{
this.id = id;
}
public int getAge()
{
return age;
}
public void setAge(int age)
{
this.age = age;
}
And my main class :
public class ProjectMain
{
public static void main(String[] args)
{
Classroom[] classarray = new Classroom[3];
//I got 3 Classroom objects here
classarray[0]=new Classroom();
classarray[1]=new Classroom();
classarray[2]=new Classroom();
classarray[0].classroomreader("class1");
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
//The problem is in here. When my code comes to the line above,
// at java.util.ArrayList.rangeCheck(Unknown Source) error comes out.
// I tried to get first object in studentobject Arraylist, and tried to set it's name
// to the variable which my text reader reads.
How can I write what I have in my mind?
Your classroomreader method reads the file but don't do much of it... maybe you want to create some instance of Students within it.
scan = new Scanner(text);
String line = scan.nextLine();
word = line.split("\t"); // won't be used
line = scan.nextLine();
word = line.split("\t"); // erased here
There you only have the last line (split) of the file in word attribute.
When creating Classroom instance studentobject list is created empty and it stays that way so you can't access first (or any) object in it.
To populate your list you may add to Classroom method like this:
public void addStudent(Student s)
{
studentobject.add(s);
}
classroom contains the following field declaration
String word[] = null;
the main class, incl the classroomreader does not set a value to this field. Yet you are going to invoke
classarray[0].getWord()[1]
which then must fail.
tip: don't use expressions like this, which can be found in your main class (at least not in early stages of development, or learning)
classarray[0].studentobject.get(0).setName(classarray[0].getWord()[1]);
resolve into variables and several steps. Compilers are smart enough to produce the same code if the context is not disturbed, ie the long expression is resolved into a single block.
Never forget that the purpose of programming languages is to make programs readable for humans. :) Code with abbreviations or "tricks" simply shows some philodoxical attitude (imho)

Java - Using Accessor and Mutator methods

I am working on a homework assignment. I am confused on how it should be done.
The question is:
Create a class called IDCard that contains a person's name, ID number,
and the name of a file containing the person's photogrpah. Write
accessor and mutator methods for each of these fields. Add the
following two overloaded constructors to the class:
public IDCard() public IDCard(String n, int ID, String filename)
Test your program by creating different ojbects using these two
constructors and printing out their values on the console using the
accessor and mutator methods.
I have re-written this so far:
public class IDCard {
String Name, FileName;
int ID;
public static void main(String[] args) {
}
public IDCard()
{
this.Name = getName();
this.FileName = getFileName();
this.ID = getID();
}
public IDCard(String n, int ID, String filename)
{
}
public String getName()
{
return "Jack Smith";
}
public String getFileName()
{
return "Jack.jpg";
}
public int getID()
{
return 555;
}
}
Let's go over the basics:
"Accessor" and "Mutator" are just fancy names fot a getter and a setter.
A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.
So first you need to set up a class with some variables to get/set:
public class IDCard
{
private String mName;
private String mFileName;
private int mID;
}
But oh no! If you instantiate this class the default values for these variables will be meaningless.
B.T.W. "instantiate" is a fancy word for doing:
IDCard test = new IDCard();
So - let's set up a default constructor, this is the method being called when you "instantiate" a class.
public IDCard()
{
mName = "";
mFileName = "";
mID = -1;
}
But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:
public IDCard(String name, int ID, String filename)
{
mName = name;
mID = ID;
mFileName = filename;
}
Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie.
Good luck.
You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables
public class IDCard {
public String name, fileName;
public int id;
public IDCard(final String name, final String fileName, final int id) {
this.name = name;
this.fileName = fileName
this.id = id;
}
public String getName() {
return name;
}
}
You can the create an IDCard and use the accessor like this:
final IDCard card = new IDCard();
card.getName();
Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.
If you use the static keyword then those variables are common across every instance of IDCard.
A couple of things to bear in mind:
don't add useless comments - they add code clutter and nothing else.
conform to naming conventions, use lower case of variable names - name not Name.

initialize object directly in java

Is that possible to initialize object directly as we can do with String class in java:
such as:
String str="something...";
I want to do same for my custom class:
class MyData{
public String name;
public int age;
}
is that possible like
MyClass obj1={"name",24};
or
MyClass obj1="name",24;
to initialize object?
or how it can be possible!
Normally, you would use a constructor, but you don't have to!
Here's the constructor version:
public class MyData {
private String name;
private int age;
public MyData(String name, int age) {
this.name = name;
this.age = age;
}
// getter/setter methods for your fields
}
which is used like this:
MyData myData = new MyData("foo", 10);
However, if your fields are protected or public, as in your example, you can do it without defining a constructor. This is the closest way in java to what you want:
// Adding special code for pedants showing the class without a constuctor
public class MyData {
public String name;
public int age;
}
// this is an "anonymous class"
MyData myData = new MyData() {
{
// this is an "initializer block", which executes on construction
name = "foo";
age = 10;
}
};
Voila!
If you have a class Person:
public class Person {
private String lastName;
private String firstName;
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
}
You can actually create a new Person object and initialize its firstName and lastName with the following:
Person person = new Person(){{
setFirstName("My FirstName");
setLastName("MyLastName");
}}
This is used quite often when defining Spring Configuration using Java code instead of XML configuration.
You have to make a constructor method for the object, which takes in parameters of the fields you want values for.
Example:
public myClass( int age, String name)
{
this.age = age;
this.name = name;
}
Then in the class you want this:
myClass class = new myClass(24, "name");
I know that with constructors, but any alternative way is present or not?
No, there are no alternatives to constructors.
That's basically one of the fundamental guarantees of the language. An object can't be constructed by any other means than through its constructors and there's no alternative syntax then the usual new ConstructorName(...).
The closest idea I can come up with would be to have a static factory method called say, mc:
class MyClass {
...
public static mc(String name, int age) {
return new MyClass(name, age);
}
}
and then do
import static some.pkg.MyClass.mc;
...
MyClass obj1 = mc("name",24);
It is possible with the keyword new and using constructors, but not like the String, that is a very special kind of object.
class MyData{
public MyData(String name, int age) {
this.name = name;
this.age = age;
}
public String name;
public int age;
}
Then you can instantiate your class this way:
MyData myData = new MyData("name", 24);
package com.company;
public class InitializationOfObject {
int a ;
int b ;
InitializationOfObject(){
}
InitializationOfObject( int r , int n){
this.a = r;
this.b = n;
System.out.println("Object initialization by constructor ");
}
void methodInitialization(int k, int m){
System.out.println("object initialization via method");
this.a = k;
this.b = m;
}
void display(){
System.out.println("k = " +a+ "m = "+b);
}
public static void main(String... arg){
InitializationOfObject io = new InitializationOfObject();
InitializationOfObject io2 = new InitializationOfObject(45,65);
io.a = io2.a;
io.b = io2.b;
io.display();
io.methodInitialization(34,56);
io.display();
io.a = 12;
io.b = 24;
System.out.println("object initialization via refrence");
System.out.println("a = "+io.a+" "+ " b ="+io.b);
}
}
//Object initializatian by construtor
k = 45m = 65
object initializaion via method
k = 34m = 56
object initialization via reference
a = 12 b =24
There are two types of Constructors in java.
Default constructor
Parameterized constructor
You should create a parameterized constructor to create your object.
The following does what you want, but not in the way that you would expect.
So in a class calling MyData, you would use
Public MyData x = new MyData();
#PostConstruct public void init() {
x.setName("Fering");
x.setAge(18);
}
So once the object is construsted, these commands are run, which allows you to populate the object before anything else runs.
So with this you do not have to use anonymous subclasses, or create new constructors, you can just take the class and then use its functions, before anything else would.
There is no alternative to constructors (along with new operator) in java during the object initialization. You have mentioned as
String str = "something"
you can initialize string that way, because String is a literal in java. Only literals can initialized that way. A a composite object can not initialized, but only can be instantiated with the new operator with the constructors.

Categories

Resources