Unknown variable in class in Java - java

I think it's stupid but I must know what that thing is (in the red circle), is it a variable or something? This is tutorial from YouTube (https://www.youtube.com/watch?v=lF5m4o_CuNg).
I want to learn some about this but when I don't even know name of that I can't search info about this.

That are variables of specific types which are available in android. They store information about objects which are defined in some xml files. Usually their purpose is to add some logic to some graphic objects like text field or button.

TL;DR: Those are called attributes
Java is an object-oriented programming language. It means that we can create classes, with attributes (variables) and methods (functions), to represent (abstract may be a better word) concepts of the real world.
Let's say we want to represent a person in our program. We need to store the person's name and their e-mail address.
We can create a class Person with 2 attributes: name and email.
public class Person {
String name;
String email;
}
Now we can create an instance of a Person, and fill the attributes with values:
public class Person {
String name;
String email;
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "Alice";
person1.email = "alice#gmail.com";
}
}
Let's say that we want to find out the e-mail provider of a Person. We can do that by creating a method.
public class Person {
String name;
String email;
public String getEmailProvider() {
String emailProvider = email.split("#")[1];
return emailProvider;
}
public static void main(String[] args) {
Person person1 = new Person();
person1.name = "Alice";
person1.email = "alice#gmail.com";
String person1EmailProvider = person1.getEmailProvider();
System.out.println(person1EmailProvider);
// This prints: gmail.com
}
}
The cool part about object-orienting is that you can create multiple instances of a Person, and fill their attributes with different values. So if you need to represent a, say, Bob, you can just Person person2 = new Person() and then set the attributes to the values that you want.
This is a very basic explanation of object-oriented programming. The internet has plenty of information about it, and I deeply recommend you to study this if you're a beginner.

Those are 3 variables.
"private" is the access modifier,
"EditText" is a variable type
"Password" is name of the variable

Related

Set compulsory field for an object

I am working on my pet ownership system and struggle at a problem. To add a resident object, I need 5 fields which are phone, postcode, name, birthday and pet. Among them, phone, postcode, and name are compulsory fields, and the others are optional. An object can only be built with the existence of compulsory fields.
How can I do that, to differentiate between compulsory and optional fields? I just taught myself the OOP system. Really need a hint. Any answer is welcome!
The best way to do this is to make sure through prompt(user input) or string check(file input) if the input has the correct fields needed to correctly create your object(class)
After this use a programmer defined constructor
Documentation for that in the link
https://docs.oracle.com/javase/tutorial/java/javaOO/constructors.html
to instantiate the object using the needed fields and I would use Set functions for optional inputs.
If the inputs do not match the needed inputs output a fail message and do not instantiate the object.
I hope this helps with your problem.
This is just an example of how you could approach the problem
public class Example{
String phone;
String postcode;
String name;
String birthday;
String pet;
public Example()
{
birthday="N/A";
pet="N/A";
}
public static void main(String[] args)
{
//Ask phone number
while(phone==null||phone=="")
{
//keep on asking
}
//Ask postcode
while(postcode==null||postcode=="")
{
//keep on asking
}
//Ask name
while(name==null||name="")
{
//keep on asking
}
//Ask birthday, and no need for checks
//Ask pet, and no need for checks
}
}

Java Arraylist change affect other variables

I am using java fx, nothing fancy in the code below, and catching the text field's focusedProperty to overwrite the newly entered value below. The code below changes a person's name that is entered in the textfield and when user clicks on cancel button it will put the old name back into the textfield. But for some reason a magic happens and whenever I set the person's name it overwrites the field in the cancelPerson variable. Could not figure out why this would happen? I get the cancelPerson from persons list before I set the new value. So how come changes in the persons list can affect an independent variable. Any idea why this would occur? Thanks.
private ObservableList<Person> persons;
private Person person;
private Person cancelPerson;
personName.focusedProperty().addListener((observable, oldValue, newValue) -> {
if (!newValue) {
final int index = personIdCombo.getSelectionModel().getSelectedIndex();
cancelPerson = persons.get(index);
final Person person = persons.get(index);
person.setName(personName.getText());
persons.set(index, person);
}
}
);
class Person{
private final StringProperty name;
public Person() {
this.name = new SimpleStringProperty("testName");
}
public SystemParams(Person person) {
this.name = person.name;
}
}
Jim Garrison's answer (suggesting the copy constructor) is correct; I
just wanted to add another answer to give a helpful way of thinking
about references in Java.
I found it helpful to think of an = assignment as a REFERS TO assignment. So, cancelPersons = persons.get(index); is basically saying:
cancelPerson REFERS TO persons.get(index);
Now, where your second line says final Person person = persons.get(index);, think of it as
final Person person REFERS TO persons.get(index);
See how they both REFER TO the same persons.get(index)? Now, whether you use cancelPerson or just person, Java is pointing back to the same overall object, not different ones.
Unless you have a new keyword somewhere, you are not actually creating a new object.
This is because person and cancelPerson are references and when you do
cancelPerson = persons.get(index);
final Person person = persons.get(index);
You end up with both variables pointing to the same object.
If you want to save a copy of person you have to do a "deep copy", that is create a new Person and copy the contents to the new object. This is usually done with what is referred to as a "copy constructor"
class Person {
public Person() { ... the no-arg constructor }
public Person(Person p) {
this.name = p.name;
... etc
}
}
In Java, class instances like instances of Person are reference types. This means that when you perform an assignment, you are merely copying a reference to an instance.
In your code, person and cancelPerson both refer to the same Person instance and any operations you do on them affect that same instance.
You could make a copy of a Person instance first if you don't want it to be modified.

How to use an object without knowing the objects' name

I'm not too sure how to word this so it makes sense, but I'll try my best.
Say I have 2 classes. My main class, and a Person class.
My main class will create some Objects from the Person class like this
public class Example {
static Person bob = new Person(23);//Age
static Person fred = new Person(34);
static Person John = new Person(28);
//..and so on
public static void main(String args[]){
..
}
}
and in my Person class..
public class Person{
private int age;
public Person(int age){
this.age = age;
}
public int getAge(){
return this.age;
}
}
Now, if I wanted the age of fred, I'd just call Fred.getAge();.
But, in my program, I don't know what person I'm getting the age of. It randomly selects one, and I need to get the name without directly calling the object. For example, I would have something like this in my Person class:
public static Object getPerson(){
//Some code to get a random integer value and store it it Var
switch(Var){
case 1:
return bob;
case 2:
return fred;
case 3:
return john;
}
}
What I would expect this to do is return an Object that I could then use like this:
public static void main(String args[]){
System.out.println(Person.getPerson().getAge());
}
What I thought that would have done was first call getPerson() which randomly returns either bob, fred, or john, and then it would call getAge(). So if getPerson() returned fred then it would be the same as doing fred.getAge();
Now, this doesnt work, and this was the only way I thought of that made sense to me.
How do I do this so it actually does what I want?
I'm very new to Java, and OOP, and this is my first time really working with different Objects. So I'm sorry if I'm using the wrong terms and explaining things weirdly.
Change
public static Object getPerson(){
to
public static Person getPerson(){
You can't call getAge on an Object, because the Object type does not have getAge() defined.
Why not put the name as a property of the Person class?
class Person {
// ... your existing code for age...
private String name;
String getName() { return name; }
// add name to constructor...
public Person(String name, int age) {
// set them up here...
}
}
The way I see it, is that name is for you as a human, but variables john are irrelivant to the program and computer.... you can even use p1 = Person("Joe", 42);
To get a person by age, you can use a Map with age as key, and person as value.
It could be the case that this is a misunderstanding, but how I'm interpreting the issue is as follows:
You need a (better) place to store all of your Person objects instead of having them as static variables.
You need a way to randomly select from wherever you're storing those objects.
Let's address the main issue first. You're creating these as static variables when they probably shouldn't be; they should just be created as entries into an array.
The way to do this is through this declaration:
Person[] people = new Person[] {new Person(23), new Person(34), new Person(28)};
The main issue now is that you have no way to refer to which person's age belongs to whom since you haven't attached a name field to any of these instances. You could do that easily:
public class Person {
private String name;
private String age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
// getters for name and age
}
...then you can instantiate your Person with two values.
new Person("Bob", 23);
Now that we've addressed one concern (which was where to store the people in the first place), now we need a way to randomly access them.
For that, we can use Random#nextInt().
Random rand = new Random();
System.out.println("Person's age - " + people[rand.nextInt(people.length)]);
This will randomly pull a Person out of the array and print their age.
If you want to get a random person within the person class you could store a reference to each person created, and then select randomly from that list
public class Person {
// A List of every Person Created.
private static final List<Person> allPeople = new ArrayList<People>();
// A source of random numbers
private static final Random rand = new Random();
...
public Person(int age) {
...
// Every time we create a new Person, store a reference to that person.
addPerson(this);
}
// synchronized as ArrayLists are not thread safe.
private static synchronized addPerson(Person person) {
allPeople.add(person);
}
...
public static Person getRandomPerson() {
// Get a random number between zero and the size of the list.
int random = rand.nextInt(allPeople.size() -1);
return allPeople.get(random);
}
Now this code is not what I would do in a production environment but it the question sounds like an exercise. A better way would be to store the people created in a List in your Example class. But trying to answer the question as you asked it.

Java: Adding Fields to Sub-Class Constructors?

For example, say I have the 3 classes Person, Student and Teacher. The Person class would have general details about the people (name, age, email etc) which both the Student and Teacher class will extend. On top of this though, these classes will also have their own unique fields (e.g. wage & courseTaught (or "tought"?) for Teacher and schoolYear & classNumber for Student). If I just show the initial code I've got, maybe someone could point me in the right direction. Because Person doesn't have a courseTaught field, currently I'm just getting the output "Josh (null)" rather than "Josh (Computer Science)". Any help would be appreciated :)
public class Main {
public static void main(String args[]){
Teacher t = new Teacher("Josh", "Computer Science");
System.out.println(t.name + " (" + t.courseTaught + ")");
}
}
public class Person {
String name;
public Person(String pName){
name = pName;
}
}
public class Teacher extends Person{
String courseTaught;
public Teacher(String tName, String tCourseTaught){
super(tName);
}
}
The problem is simpler than you think. You're on the right track but you forgot to assign courseTaught in your Teacher constructor. The initial value of courseTaught is null and it stays that way because you never assign it to anything.
You'd want something like this:
public Teacher(String tName, String tCourseTaught){
super(tName); // <- takes care of Persons's field
courseTaught = tCourseTaught; // <- but don't forget to set the new field, too.
}
And yes, "taught" is the correct word.
As an aside, since you did tag your question "oop", you may want to check out this article on encapsulation for some information about the use of "getters" and "setters".

Dynamic variable names in Java so each new object has separate name

How can I do such a thing?
String N = jTextField0.getText();
MyClass (N) = new Myclass();
Is it even possibe?
Or as my question's explains, how can I just make a method to create a new object of my specified class just with a different name each time I call it.
I really searched everywhere with no luck.
Thanks in Advance
P.S.
I wish you guys can excuse me for not being clear enough, Just to say it as it is, I made a textfield to get the name of someone who wants to make an account, and I made a class named "Customer". and a button named "Add". Now I want every time "Add" is clicked, compiler take what is in my textfield and make an object of the class "Customer" named with what it took from the textfield
It was too hard to read it in comments so I updated my question again, so sorry.
I'm stuck so bad. I suppose my problem is that I didn't "understand" what you did and only tried to copy it. This is what I wrote:
private void AddB0MouseClicked(java.awt.event.MouseEvent evt) {
String name = NameT0.getText();
Customer instance = new Customer(Name);
Customer.customers.add(instance);
and this is my Customer class:
public class Customer{
String name;
public Customer(String name){
this.name = name;
}
public String getName(){
return name;
}
static ArrayList<Customer> customers = new ArrayList<Customer>();
Variable names must be determined at compile time, they are not even part of the generated code. So there is no way to do that.
If you want to be able to give your objects names, you can use
Map<String, MyClass> map = new HashMap<>();
Add objects to the map like this (e.g):
map.put(userInput, new MyClass());
and retrieve objects like this:
MyClass mc = map.get(userInput);
I'm not entirely sure what you mean by...
how can I just make a method to create a new object of my specified
class just with a different name each time I call it
...but if I'm interpreting you correctly, I believe what you're trying to do as make MyClass accept a constructor parameter. You can do:
public class MyClass {
private String name;
public MyClass(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then to create a new instance of MyClass, do:
String name = jTextField0.getText();
MyClass instance = new MyClass(name);
instance.getName(); // returns the name it was given
EDIT
Since you've added clarifications in the comments since I first answered this question, I thought I would update the answer to portray more of the functionality that you're looking for.
To keep track of the MyClass instances, you can add them to an ArrayList. ArrayList objects can be instantiated as follows:
ArrayList<MyClass> customers = new ArrayList<MyClass>();
Then for each MyClass instance you wish to add, do the following:
customers.add(instance);
Note that the ArrayList should not be reinstantiated for each instance that you wish to add; you should only instantiate the ArrayList once.

Categories

Resources