I have researched, and although this is a really simple issue, I am not sure how to solve it.
The code I have looks like this:
public class Playlist {
public Playlist(String name) {
}
}
Separate files of course:
#Test
public void CreatePlaylist(){
Playlist myPlaylist = new Playlist("Workout Playlist");
}
I am trying to print the actual name of this new playlist "workout playlist" but I can't seem to find a way to do so.
You need to store the name of your playlist in an instance variable. For instance:
public class Playlist {
private final String name;
public Playlist(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then you can print it with:
System.out.println(myPlayList.getName());
If you want to make the name mutable, then get rid of the final modifier and add a setName(String) method.
write get method to name or override toString method in the class
public class Playlist {
private String name;
public Playlist (String name) {
this.name = name;
}
public String getName() {
return name;
}
#Override
public String toString() {
return "Playlist [name=" + name + "]";
}
}
Print the name using
System.out.println(playlistObject.getName());
or
System.out.println(playlistObject).
I would prefer setting a getter method over toString() though.
public class Playlist {
private String name;
public Playlist(String name) {
this.name = name;
}
public String getName() {
return name;
}
}
Then to show the name:
#Test
public void CreatePlaylist(){
Playlist myPlaylist = new Playlist("Workout Playlist");
System.out.println(myPlaylist.getName());
}
You are not at all storing the 'name' property in your object. So obviously you can't access name. One way is
public class Playlist {
public String name;
public Playlist(String name) {
this.name = name;
}
}
Now you should be able to access your attribute from your testcase like this.
#Test
public void CreatePlaylist(){
Playlist myPlaylist = new Playlist("Workout Playlist");
System.out.println(myPlaylist.name);
}
Related
I have a java bean class such as :
public class EncBean {
private String name;
private String ReversedBinary;
private String ConcatenatedData;
public String getReversedBinary() {
return ReversedBinary;
}
public void setReversedBinary(String ReversedBinary) {
this.ReversedBinary = ReversedBinary;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getConcatenatedData() {
return ConcatenatedData;
}
public void setConcatenatedData(String name) {
this.ConcatenatedData = ConcatenatedData;
}
}
and I tried to set a value for the private java bean field(ConcatenatedData) as follow :
public EncBean conctdat(){
EncBean encBean4 = new EncBean();
encBean4.setConcatenatedData(inputkey.concat(var));
return encBean4;
}
and in main i tried to access this value as:
mainenc concatdata =new mainenc();
EncBean encbeandata = concatdata.conctdat();
System.out.println("concatenated data is: "+encbeandata.getConcatenatedData());
but it gives me null
concatenated data is: null
You should fix implementation of setConcatenatedData() to :
public void setConcatenatedData(String name) {
this.ConcatenatedData = name; // instead of this.ConcatenatedData = ConcatenatedData
}
The first one is:
public void setConcatenatedData(String name) {
this.ConcatenatedData = name;
}
Second one, you should double check if inputkey.concat(var) is null.
You can do it by Getter & Setter.
This will help:
setConcatenatedData(String name) {
this.ConcatenatedData = name;
}
I need to write some code which is as follows:
public class Person {
public static final String NAME;
public Person(String NAME) {
this.NAME = NAME;
}
}
public class Player extends Person {
public Peter(String name) {
super(name);
}
}
It's basically, I want the Player class to have a static final field called NAME, that is being initialized somewhere else, without manually writing in every class public static final String NAME = "Peter".
Is it possible?
As it has been said in the comments, you have poorly declared your NAME variable. In actuality, you don't want it to be static (although you can keep the final modifier, if you want). Your code should, instead, be something along the lines of:
public class Person {
public final String name;
public Person(String name) {
this.name = name;
}
}
public class Player extends Person {
public Player(String name) {
super(name);
}
}
Every person should have their own name; you don't want all objects to be sharing one NAME field
I do not know if I fully understand your question, but I think you have a few mistakes in your code. Like declare name of person as static variable, because static variables are often used as variables for the entire class, and if you changed the name, would change the name to the entire class, not for one instance. Also final is wrong, because you cannot set final variable.
I would do something like this:
public class Person {
private String name;
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Override
public String toString() {
return String.format("Person: %s", this.getName());
}
}
public class Player extends Person{
public Player(String name) {
super(name);
}
public String toString(){
return String.format("Player: %s", this.getName());
}
}
public class Match {
private Player player_one;
private Player player_two;
public Match(Player player_one, Player player_two) {
this.player_one = player_one;
this.player_two = player_two;
}
public Player getPlayer_one() {
return player_one;
}
public void setPlayer_one(Player player_one) {
this.player_one = player_one;
}
public Player getPlayer_two() {
return player_two;
}
public void setPlayer_two(Player player_two) {
this.player_two = player_two;
}
#Override
public String toString() {
return String.format("Right now are playing %s VS %s",player_one.getName(), player_two.getName());
}
}
public class PlayerTest {
public static void main(String[] args) {
Player peter = new Player("Peter");
Player anna = new Player("Anna");
Match tennisMatch = new Match(peter, anna);
System.out.println(tennisMatch.toString());
}
}
I static field (variable) only exists once for all instances of your class. Therefore what you try does not work by design.
What value would you expect the field to have after you created three different instances of this class using different parameters?
A final variable cannot be changed once it got initialized. For static variables this happens before the first instance of the class is even constructed. At the moment the constructor is executed the field cannot be changed anymore.
To initialize a static final variable you have to assign a value directly at the definition using the = operator or you have to do it in a static initializer which looks like this:
public class FooBar {
public static final String STATIC_VARIABLE;
static {
STATIC_VARIABLE = "Hello World";
}
}
You can make it like this:
private static final NAME;
public Player(String name){
NAME = name;
}
A final varible can be initialized once only if it wasn't initialized yet.
So in this way the constructor is helping you make it.
I'm new to Android and I'm having a problem using String variables from resources in my code. I tried a couple of solutions found on the internet and Android API Guides, but they didn't work in this specific case, could also be me not using them correctly.
To be more specific, I have a Master/Detail flow activity and I would like to use resource strings as item names for multilanguage purposes, but I have a problem with recovering actual strings.
The error I get is:
Cannot resolve method 'getString()'
Here is my code based on android studio dummy file
public class Categories {
public static List<CatName> ITEMS = new ArrayList<CatName>();
static {
String temp = getString(R.string.cat_n1);
addItem(new CatName("1", temp);
}
private static void addItem(CatName item) {
ITEMS.add(item);
}
public static class CatName {
public String id;
public String name;
public FieldCat(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}}
You need to specify the resource. Try this,
getResources().getString(R.string.cat_n1);
getString(int resId): Return a localized string from the application's package's default string table.
getResources().getString(int id): Returns the string value associated with a particular resource ID. It will be stripped of any styled text information.
Try using it with a constructor passing the context and calling getstring on that
public class Categories {
public static List<CatName> ITEMS = new ArrayList<CatName>();
public Categories(Context ct)
{
String temp = ct.getString(R.string.abc_action_bar_home_description);
addItem(new CatName("1", temp));
}
private static void addItem(CatName item) {
ITEMS.add(item);
}
public static class CatName {
public String id;
public String name;
public CatName(String id, String name) {
this.id = id;
this.name = name;
}
#Override
public String toString() {
return name;
}
}}
I have a couple to class in which I'm getting and setting a few things and then finally calling it in my main method. But when I call my class in the main method it just gives me the object instead of name,address and age. I know this structure is very complicated but I want to keep this structure because later on I will be adding a lot of things to this. It would be AMAZING if someone could tell me how to do this. I would really appreciate this. Below is my code for all my classes
This is my first class
public class methodOne
{
public String getName()
{
String name = "UserOne";
return name;
}
public int getAge()
{
int age = 17;
return age;
}
public String getAddress()
{
String address = "United States";
return address;
}
}
This is my second class
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
This is my third class
public class methodThree {
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
public methodThree()
{
this.methodOneInMethodThree = new methodOne();
this.methodTwoInMethodThree = new methodTwo(methodOneInMethodThree);
}
public methodTwo getMethodTwoInMethodThree() {
return methodTwoInMethodThree;
}
public void setMethodTwoInMethodThree(methodTwo methodTwoInMethodThree) {
this.methodTwoInMethodThree = methodTwoInMethodThree;
}
}
This is my fourth class which is the method maker
public class methodMaker {
public methodThree brandNewFunction(methodTwo object)
{
methodThree thirdMethod = new methodThree();
thirdMethod.setMethodTwoInMethodThree(object);
return thirdMethod;
}
}
This is my main class which calls methodMaker. What I want to achieve is that when I print the value it should print the name,address and age but instead it just prints trial.methodThree#4de5ed7b
public class mainClass {
public static void main(String args[])
{
methodMaker makerOfMethods = new methodMaker();
methodOne one = new methodOne();
methodTwo object = new methodTwo(one);
System.out.println(makerOfMethods.brandNewFunction(object).toString());
}
}
What you need to do is to override the default implementation of the .toString() method in the objects you want to print out:
#Override
public String toString()
{
return "Name: " + this.name;
}
EDIT:
I do not know exactly where you are printing, and you naming convention doesn't really help out, but from what I am understanding, you would need to implement it in all of you classes since they all seem to be related to each other.
So, in your methodOne class (can also be applied to methodTwo):
#Override
public String toString()
{
return "Name: " + this.name + " Age: " + this.age + " Address: + " this.address;
}
In your methodThree class:
private methodTwo methodTwoInMethodThree;
private methodOne methodOneInMethodThree;
#Override
public String toString()
{
StringBulder sb = new StringBuilder();
if(this.methodTwoInMethodThree != null)
{
sb.append("Method 2:").append(methodTwoInMethodThree.toString());
}
if(methodOneInMethodThree != null)
{
sb.append("Method 1:").append(methodOneInMethodThree.toString());
}
return sb.toString();
}
When you call
MyClass myObject = new MyClass();
System.out.println(myObject);
Implicitly , java calls instead
System.out.println(myObject.toString());
So, if in MyClass, you override toString(), then whatever your toString method returns is what's gonna be printed.
Side note: are you confusing classes and methods? Methods are functions in your classes, classes are wrappers around a bunch of attributes and methods. Your naming is confusing.
try this code:
public class methodTwo
{
String name;
String address;
int age;
public methodTwo(methodOne objectOne)
{
name=objectOne.getName();
address=objectOne.getAddress();
age=objectOne.getAge();
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String toString(){
return name+" "+address+" "+age;
}
}
Are you printing the object using println()?
From the docs, println():
calls at first String.valueOf(x) to get the printed object's string value
This string value is obtained from the object's toString() method, which:
returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object
So if you want to print anything other than this you have to override the toString() method in your object and return a string containing whatever you want.
Just google "override tostring java" and you will see a ton of examples.
I'm coming to Java from Python and thought that this is basically like Python's self...but this small code confuses me. Functionally, this code:
public class Test {
private String name;
public Test(String givenName)
{
this.name = givenName;
}
public String nameGet()
{
return this.name;
}
public static void main(String[] args)
{
Test example = new Test("Hello Guys");
System.out.println(example.nameGet());
}
}
does the same exact thing as this code:
public class Test {
private String name;
public Test(String givenName)
{
name = givenName;
}
public String nameGet()
{
return name;
}
public static void main(String[] args)
{
Test example = new Test("Hello Guys");
System.out.println(example.nameGet());
}
}
Since this, pardon the pun, seems to be the case, what then is the point of referring to this when working within the class?
public Test(String givenName)
{
this.name = givenName;
}
The this. is not needed in this case or in the get method). It is commonly used when the code is like this instead:
public Test(String name)
{
this.name = name;
}
Which tells the compiler to set the instance variable (this.name) to the local variable (name).
Some people do it to be very clear that they are using an instance variable.
It's often not needed but may be necessary in case of ambiguity.
Say your constructor parameter was called name then there would be no way of determining which variable you're referring to.
Thus you would have to use:
public class Test {
private String name;
public Test(String name) {
this.name = name;
}
}
(On a side note; if you'll ever work with inner classes and you've got name ambiguity you use OuterClass.this:
public class Test {
private String name;
private class InnerTest {
InnerTest(String name) {
Test.this.name = name;
}
}
public Test(String name) {
new InnerTest(name);
}
}