I'd like to do something like this:
create a class with the following properties: String name; int atomicNumber; String symbol; double mass;
create an initializer so you can just do new Element("Hydrogen", 1, "H", 1.0079) and a toString method.
now create an object for each element. note that now, you only have one line of code per element. you can store these in an array (or a dictionary that uses the name as the key).
when the user inputs the name, you can just look for it in the array (or just get the value from the key in the dictionary) and call toString on the object.
why this way? imagine that now you have to add a line in your output with the number of valence electrons for each atom. this would require a line or two in toString, rather than one line for each element.
How would I go about doing this? What would the class with the properties look like?
I tried making one:
public class Structure {
String name;
int age;
String color;
public void add(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
}
But I'm not quite sure how to go on, and Structure.add("Adele",25,"Grey"); works but doing it with another overwrites the data.
You'll want to make a new object for each element. So the class's "add" method, shouldn't be called "add". Since it won't be adding anything. Instead, let's make that a constructor. Like this:
public Structure(String name, int age, String color) {
//The inside stays the same
}
Now we can make objects like this:
Structure s = new Structure("matthew", 22, "BLUE");
We can store those objects in an array like this:
Structure[] structures = new Structures[numStructures];
for(int i = 0; i < numStructures; i++) {
structures[i] = new Structure("whatever", 99, "some color")l
}
You're supposed to store multiple Structure objects in a list.
public class Structure {
String name;
int age;
String color;
public Structure(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
}
Then, in the place you are creating objects.
List<Structure> list = new ArrayList<>();
list.add(new Structure("john",25,"blue"));
list.add(new Structure("sally",15,"green"));
list.add(new Structure("mark",35,"red"));
The point of a class is that you can create new objects of that classtype. In Java you create instances of a class like so:
Structure instance1 = new Structure();
In your case, you have an add method, so you could call that on your new object to set its properties:
instance1.add("Adele", 25, "Grey");
but it would make more sense to define a constructor:
public Structure(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
I would suggest reading up on some basic object-oriented programming concepts.
Your "first try" should be
public class Structure {
String name;
int age;
String color;
public Structure(String name, int age, String color) {
this.name = name;
this.age = age;
this.color = color;
}
}
Instead of writing a method add, you create a constructor: no return type (remove the void), and must use the same name as the class name.
For your question, use the properties name, atomicNumber, symbol and mass instead of the properties name, age and color as in your example. You must also use the class name Element instead of Structure.
Related
Forgive me if this is a duplicated question but I'm a beginner in Java and I'm currently trying to get the parameter value from a class called Name and pass that value into another class called Student.
Name Class:
public class Name
{
public String studentName;
public Name(String fullName)
{
studentName = fullName;
}
}
Student Class:
public class Student
{
private Name studentName;
private String id;
private int credits;
public Student(String studentID)
{
studentName = new Name("");
id = studentID;
credits = 0;
}
}
What I want to do is to get the parameter value of fullName which is set in the Name class and pass it in studentName = new Name(""); for the Student class instead passing in an empty string to retrieve the name.
What do you mean by "taking the parameter value of fullName, which is set in Name class"? A class will not have a value, you need access to the instance of this class. I'm pretty sure you will have some kind of control class, e.g. where your main() resides.
At some point you will have created a Name instance:
Name n = new Name("Brandon");
Using this instance of Name class, you can access the actual value:
Student s = new Student("4711", n.studentName);
, assuming you also have included an additional parameter in your Student constructor:
public class Student
{
private Name studentName;
private String id;
private int credits;
public Student(String studentID, String name)
{
studentName = new Name(name);
id = studentID;
credits = 0;
}
}
, but this would result in you having 2 different Name objects.
Another option is to pass the object itself as parameter, so both of your objects reference to same object. Changing studentName of either n.studentName and s.studentName would in theoretically result in the value of the respective other being changed as well (I can recall some discussions regarding that topic in Java though).
public class Student
{
private Name studentName;
private String id;
private int credits;
public Student(String studentID, Name nameObject)
{
studentName = nameObject;
id = studentID;
credits = 0;
}
}
, which is instantiated by
Name n = new Name("Brandon");
Student s = new Student("4711", n);
You should definitely start reading introductions into object oriented programming, as there are quite a lot of misassumptions just in those few lines of code. The difference between class and object is crucial, also it's usual in those scenarios to have getters/setters rather than public variables in classes. To achieve the kind of dependency you want to have, you might want to look into composition and aggregation in the context of object-orientation. Also the difference between pass-by-value and pass-by-reference is worth looking into.
Assume we have the following class:
class Person {
private int age;
private String name;
public Person(int age, String name){
this.age = age;
this.name = name;
}
// getters and setters
}
and we also have some class:
class SpecialClass {
public int giveNumber(Person p) {
...
return (int)(...)
}
}
Assume I want to mock an object of SpecialClass that if 'giveNumber' is invoked with a Person object that has name property equals to 'John', then 'giveNumber' will retrieve 500.
For example,
SpecialClass sc = mock(SpecialClass.class);
when(sc.giveNumber(p with name = "John").thenReturn(500);
Is there any way to do it with Mockito?
You can use org.mockito.ArgumentMatchers.argThat(...) passing it a lambda that matches the desired instance. In this case the lamdba would be something like
(person) -> "John".equals(person.getName())
Putting it together:
SpecialClass sc = mock(SpecialClass.class);
when(sc.giveNumber(argThat((person) -> "John".equals(person.getName())))).thenReturn(500);
I want to implement a class for Museum objects.
Each museum Has a name and can contain different Art objects.
Art Objects are implemented within another class
Each Art Object has 3 attributes (name, artist, value)
class Pieces_of_art {
private String name;
private String artist;
private float value;
Pieces_of_art(String name, String artist, float value) {
this.name = name;
this.artist = artist;
this.value = value;
}
}
class museum {
Arraylist<Pieces_of_art> set = new ArrayList<>();
//Initializing Arraylist with type "Piece_of_art" called set and it's empty?
String name;
museum(String name, Arraylist<Pieces_of_art> set) {
this.name = name;
set = new ArrayList<Piece_of_art>();
}
}
I don't really understand how it is possible to use and arraylist within a constructor as an empty parameter
There seems no hard to understand. Constructor is a special kind of method. As a method, why not take a List as parameter?
By the way, in your case, you have initialized set parameter already. If you want to make use of it. try below
museum(String name, Arraylist<Pieces_of_art> set) {
this.name = name;
this.set.addAll(set);
}
I am writing a class for a project regarding the Titanic. The instructions say
Passenger: Represents a passenger of the Titanic, with attributes (instance variables):
Instance data:
status (an integer: 1, 2, 3, or 4, representing 1st, 2nd, 3rd class or crew
child (a boolean: true = child, false = adult)
sex (a String: “male” or “female”)
survivor (a boolean: true/false indicating whether this passenger survived)
Here is my code currently, not sure if it is off or if I am putting things in the wrong place
//********************************************************************
// Passenger.java Author:
//
// Represents passenger on Titanic.
//********************************************************************
import java.text.NumberFormat;
public class Passenger
{
int status;
boolean child;
String sex;
boolean survivor;
//-----------------------------------------------------------------
// Creates a new DVD with the specified information.
//----------------------------------------------------------------
public Passenger (int 1, int 2,int 3, int 4, boolean true, boolean false, String m, String f)
{
1=1stclass;
2=2ndclass;
3=3rdclass;
4=crew;
true=child;
false=adult;
m=male;
f=female;
}
}
Your constructor is incorrect
for constructor parameters you can't use actual values, you must use names for them. It must be:
`public Passenger( int status, boolean child, String sex, boolean survivor){
this.status = status;
this.child = child;
this.sex = sex;
this.survivor = survivor;
}
//you also can add setters and getters for your class attributes
public void setStatus(int status) {
this.status = status;
}
public int getStatus() {
return status;
}
//so you can create another setters and getters for all your attributes`
Now try to replace your constructor with this one.
The most common way to do this would be the following:
public class Passenger {
int status;
boolean child;
String sex;
boolean survivor;
public Passenger (int status, boolean child, String sex, boolean survivor) {
this.status = status;
this.child = child;
this.sex = sex;
this.survivor = survivor;
}
}
but since you probably do not know what this means, let us just come up with new variable names instead:
public class Passenger {
int status;
boolean child;
String sex;
boolean survivor;
public Passenger (int c_status, boolean c_child, String c_sex, boolean c_survivor) {
status = c_status;
child = c_child;
sex = c_sex;
survivor = c_survivor;
}
}
A constructor is called when an instance of this class is created by for example
new Passenger(2, true, "female", false)
after which the constructor will take these four values, and do what it is supposed to do. In our case, it will take these values and assign them to the four fields status, child, sex, and survivor.
To be able to tell the constructor to do this, we give these parameters a name (so we can refer to them) - in our example: c_status, etc. Then we tell the constructor to take the value of c_status and put it into status where it is saved until the object gets destroyed.
I suggest you open a Java-book and read through it. I am writing this answer mostly to give you a quick-fix.
I'm currently working on this code, I want to pass an ID to a member function to get the object.
public class Car {
private int _ID;
private String name;
private String model;
Car(int _id, String name, String model){
this._ID = _id;
this.name = name;
this.model = model;
}
....
public static Car getCar(int _id){
Car mCar;
//TODO: Algo to get car
return mCar;
}
}
Is there any way I can get the object in this way?
Any help is appreciated!
Thank You!
You'll need to keep a Map of objects by key. Here's one way to do it:
public class Car {
private int _ID;
private String name;
private String model;
Car(int _id, String name, String model){
this._ID = _id;
this.name = name;
this.model = model;
carsById.put(_id, this); // <-- add to map
}
....
private static Map<Integer, Car> carsById = new HashMap<>();
public static Car getCar(int _id){
return carsById.get(_id);
}
}
There's no predefined way to do that. You'd have to have Car or something else maintain a Map<Integer,Car> or similar of cars. This would usually be best done not in Car itself, but in the code using it.
Unless you have a list (or map or tree or anything else suitable) of created Car, it's not possible with your current code only. A good practice is to separate this list out of Car class, maintained elsewhere. But if you insist, shmosel provides one way.