This question already has an answer here:
Get object name in Java [closed]
(1 answer)
Closed 7 years ago.
I would like to know if we can get the name of instance name in Java. For example:
class A {
public void run() {
System.out.println("Name: " + ????);
}
}
public class Main
{
public static void main(String[] _args) {
A p = new A();
A q = new A();
p.run();
q.run();
}
}
My expectation result would be:
Name: p
Name: q
Is it anyway to get this?
That's impossible in Java, not even available through reflection. Your best bet is you have a String field where you will store the name of the variable and fill this field when creating the object reference.
class A {
private final String name;
public A(String name) {
this.name = name;
}
public void run() {
System.out.println("Name: " + this.name);
}
}
//...
A p = new A("p");
A q = new A("q");
Related
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 1 year ago.
I'm trying to create a class called "NewType" where there is a string as attribute. In another class in the same package I created an ArrayList<NewType>.
How can I print the string parameters that I pass every time I create a NewType object (new NewType("Hello"))? Because using a for and printing just the object, it prints only the address of the new objects created. I know that I could just create an ArrayList<String>, but I need this also to understand how to work with the class types.
Here is what I tried:
Token j=new Token(part); //Token is th e "NewType" class type
tokenfinal.add(j); //tokenfinal is the ArrayList<Token>
//CLASS TOKEN
public class Token {
public String tok;
public Token(String tok) {
this.tok=tok;
Let's see the following example:
public class Main {
static class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return String.format("Person name: %s", this.getName());
}
}
public static void main(String[] args) {
List<Person> personList = new ArrayList<>();
personList.add(new Person("Test_Name"));
personList.add(new Person("Name_Name"));
personList.forEach(System.out::println);
}
}
Result:
Person name: Test_Name
Person name: Name_Name
You need to override toString() method in your Token class and customize it to return your field String tok or any other field you create
I am not sure if I understood your question, but you can do print value of the input string via override the toString method int the NewType class.
public class NewType {
private String text;
public NewType(String str) {
text = str;
}
#Override
public String toString() {
return text;
}
}
By this, printing the class instance in print or println will call the overrided toString method.
This question already has answers here:
Avoiding overwriting objects in ArrayList
(2 answers)
Closed 3 years ago.
The data which was previously stored in an array list , is getting replaced by updated data.
code is shown below
public class Telivision {
private String tvBrand;
private Double tvCost;
private Integer tvDimension;
private String tvScreen;
public String getTvBrand() {
return tvBrand;
}
public void setTvBrand(String tvBrand) {
this.tvBrand = tvBrand;
}
public Double getTvCost() {
return tvCost;
}
public void setTvCost(String brand) {
if(this.tvBrand.equalsIgnoreCase("Samsung")){
this.tvCost = 100*1.5;
}else if(this.tvBrand.equalsIgnoreCase("Sony")){
this.tvCost = 100*2.0;
}
}
public Integer getTvDimension() {
return tvDimension;
}
public void setTvDimension(Integer tvDimension) {
this.tvDimension = tvDimension;
}
public String getTvScreen() {
return tvScreen;
}
public void setTvScreen(String tvScreen) {
this.tvScreen = tvScreen;
}
#Override
public String toString() {
return "Telivision [tvBrand=" + tvBrand + ", tvCost=" + tvCost + ", tvDimension=" + tvDimension + ", tvScreen="
+ tvScreen + "]";
}
TESTER IS AS SHOWN BELOW
public class TelivisionTester {
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
telivision.setTvBrand("Sony");
telivision.setTvDimension(36);
telivision.setTvScreen("Led");
telivision.setTvCost("Sony");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
}
the output which is expected is as shown below
[Telivision [tvBrand=SAMSUNG, tvCost=150.0, tvDimension=40, tvScreen=Led],
Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led]]
but the output observed is as shown below
[Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led],
Telivision [tvBrand=Sony, tvCost=200.0, tvDimension=36, tvScreen=Led]]
kindly let me know what mistake i am doing in this code
You're list is not being overwritten. You are are adding the same instance of the class twice instead of creating a new one with the new attributes. Because the original istance changed you get the same attributes for both entries in the list. Create a new instance of the object for each Television you add to the list.
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
Telivision secondTelivision = new Telivision();
secondTelivision.setTvBrand("Sony");
secondTelivision.setTvDimension(36);
secondTelivision.setTvScreen("Led");
secondTelivision.setTvCost("Sony");
telList.add(secondTelivision);
System.out.println(telList);
}
You forgot to declare a second Telivision to separate the two.
public class TelivisionTester {
public static void main(String[] args) {
Telivision telivision = new Telivision();
ArrayList<Telivision> telList = new ArrayList<Telivision>();
telivision.setTvBrand("SAMSUNG");
telivision.setTvDimension(40);
telivision.setTvScreen("Led");
telivision.setTvCost("Samsung");
telList.add(telivision);
System.out.println(telList);
System.out.println(telivision.getTvBrand()+"Cost is "+telivision.getTvCost());
Telivision television2 = new Television();
telivision2.setTvBrand("Sony");
telivision2.setTvDimension(36);
telivision2.setTvScreen("Led");
telivision2.setTvCost("Sony");
telList.add(telivision2);
System.out.println(telList);
System.out.println(telivision2.getTvBrand()+"Cost is "+telivision2.getTvCost());
//telList.addAll(telList);
//System.out.println(telList);
}
}
Also “Telivision” is actually spelled Television
This question already has answers here:
What does the 'static' keyword do in a class?
(22 answers)
Closed 4 years ago.
I've been running through a few tutorials for Java, they all say to make a new variable when calling classes. Why is this? I've tested some code and it works without doing this.
I've been using python for quite a while now so I'm used to using a dynamic language.
Please see some code I've been playing around with below:
import java.util.Scanner;
class MyClass {
static String myName(String name) {
return ("Your name is: "+name);
}
static String myAge(Integer age){
return ("Your age is: "+age);
}
static String myGender(String gender){
return ("You are: "+gender);
}
}
class Test{
public static void main(String [ ] args){
Scanner ui = new Scanner(System.in);
MyClass user = new MyClass();
//Output with new variable of class - user
String input = ui.next();
String newname = user.myName(input);
System.out.println(newname);
//Output calling class directly
Integer input1 = ui.nextInt();
String newage = MyClass.myAge(input1);
System.out.println(newage);
//Output with new variable of class - user
String input2 = ui.next();
String newgender = MyClass.myGender(input2);
System.out.println(newgender);
}
}
Thanks for your time.
If everything in the class is static (as in the code you posted), then there's no need to create instances of the class. However, if the class were to have instance fields and/or methods, then the story is different. For instance, consider a class like this:
class Person {
private String name;
private int age;
private String gender;
public Person(String name, int age, String gender) {
this.name = name;
this.age = age;
this.gender = gender;
}
String myName() { return "Your name is: " + name; }
String myAge() { return "Your age is: " + age; }
String myGender() { return "You are: " + gender; }
}
Then you could create several Person instances with different internal state and use them interchangeably in your code:
public static void main(String[] args) {
Person jim = new Person("Jim", 40, "male");
Person sally = new Person("Sally", 12, "female");
report(jim);
report(sally);
}
private static report(Person person) {
System.out.println(person.myName());
System.out.println(person.myAge());
System.out.println(person.myGender());
}
If we create any member with static keyword it get memory at once to all objects, static keyword we used when we have common properties in class and we don't want to create separate memory to all instances objects ... it doesn't need to create instance variable to call it and this static block is shareable to to all objects.... for example if we have Animal class and we want to describe 5 different type of dog's ... than we don't define color, size like properties as static ... because they all have their own different size and color.... I hope you get it
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.
I am learning Java and so, I want easy and understandable answer.
You will know what I mean when you see the code below:
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Playeri user = new Playeri();
Enemyu enem = new Enemyu();
Scanner input = new Scanner(System.in);
user.name = input.nextLine();
user.showName();
enem.showUserName();
}
}
class Playeri {
String name;
void showName() {
System.out.println("Your name is " + name + ".");
}
}
class Enemyu {
Playeri enemUser = new Playeri();
void showUserName() {
System.out.println("Hey, bro! Are you " + enemUser.name + "?");
}
}
Suppose input is: John.
Then, output will be:
Your name is John.
Hey, bro! Are you null?
Here, I want John instead of null in output(line 2).
But I can't.
How can I access the same input to other classes (for e.g: Enemyu) other then the class having the declararion of the variable in which input is set (for e.g: Playeri)?
In Other Words:
How can multiple classes access the same value of variable that is set in a class through main method?
Please answer my question!
Thank you very much!
EDIT: Sorry for incorrect indentation in the code.
You are not setting value to the object's name variable.
public static void main (String[] args) {
Playeri user = new Playeri();
Enemyu enem = new Enemyu();
Scanner input = new Scanner(System.in);
user.name = input.nextLine();
user.showName();
enem.showUserName();
}
}
class Playeri {
String name;
void showName() {
System.out.println("Your name is " + name + ".");
Enemyu.enemUser.name=name; // Set it like this
}
}
class Enemyu {
static Playeri enemUser = new Playeri(); // make it static
void showUserName() {
System.out.println("Hey, bro! Are you " + enemUser.name + "?");
}
}
Output -
John
Your name is John.
Hey, bro! Are you John?
This solves your problem, but It is recommended you use setter-getter method.
You can pass it as a parameter to that method.
void showName(String myName) {
System.out.println("Your name is " + myName + ".");
}
and
enem.showUserName(user.name);
or, you could set it the way you did with the user class.
or, you could use mutators (setters/getters) in this case, a set-method, or pass it as a parameter to the constructor of the class.
Here is a fixed version of your code. The problem that you had was that you created two separate instances of Playeri and only set the name on one of the instances. This solution only creates a single instance of Playeri, thus bypassing the problem.
import java.util.Scanner;
public class Foo {
public static void main (String[] args) {
Playeri user = new Playeri();
Enemyu enem = new Enemyu(user);
Scanner input = new Scanner(System.in);
user.name = input.nextLine();
user.showName();
enem.showUserName();
}
}
class Playeri {
String name;
void showName() {
System.out.println("Your name is " + name + ".");
}
}
class Enemyu {
Playeri enemUser;
public Enemyu( Playeri p ) {
this.enemUser = p;
}
void showUserName() {
System.out.println("Hey, bro! Are you " + enemUser.name + "?");
}
}
In your Enemyu class create getters and setters for your field variables.
Inside Enemeyu...
private String name;
...
public void setName(String newName) {
this.name = newName;
}
public String getName() {
return this.name;
}
...
Then inside your main method...
...
Enemyu enem = new Enemyu();
enem.setName("John");
Granted you might also want to provide your class with an overidden toString() method (which in your case is your showName). However, in your case; I don't think that will be necessary.
Your problem was that you were never setting the name field in the object.