.valueOf using another class's private variable - java

BaseExample Class (I am not allowed to make the variable protected on this example):
public class BaseExample {
private int a;
public BaseExample(int inVal) {
a = inVal;
}
public BaseExample(BaseExample other){
a = other.a;
}
public String toString(){
return String.valueOf(a);
}
}
DerivedExample Class:
public class DerivedExample extends BaseExample {
private int b;
public DerivedExample(int inVal1, int inVal2){
super(inVal2);
a = inVal2;
}
}
The super method worked. Now how would I call it if I am asked this:
**Returns a reference to a string containing the value stored in the inherited varible a followed by a colon followed by the value stored in b public String toString()**
I have tried this:
public String toString(){
int base = new BaseExample(b);
return String.valueOf(base:this.b);
}
If I put two returns, it would give me an error of unreachable code. And if I put a super inside the valueOf it doesn't work. And this doesn't work as well. How is this executed?

I think you misunderstood the requirement, you need to print a which is located in the parent class separated by a colon concatenated with b which is in the current class.
String.valueOf(base:this.b)
This is incorrect syntax, what you want is
super.toString() + ":" + this.b;

Related

Java abstract class for giving unique ID not working - all of objects have same ID

I have problem with my Java program. Class Wolumin is responsible for giving unique ID for the objects in Object tab, but it always gives same number to every object. I tried giving variety of acces privilages to it, but nothing seems to be working. In this case each tab object have ID=4, but i want it to be in order :1,2,3,4...
public class First {
public static void main(String args[]){
Object[] tab = new Object[4];
tab[0]=new Ksiazka("Malysz","Homies");
tab[1]=new Ksiazka("Pudzian","Malta");
tab[2]=new Czasopismo("Bravo","420");
tab[3]=new Czasopismo("Grzyby","2137");
System.out.println(tab[0].toString());
System.out.println(tab[1].toString());
System.out.println(tab[2].toString());
System.out.println(tab[3].toString());
}
}
abstract class Wolumin{
static int id;
Wolumin(){id++;};
}
class Ksiazka extends Wolumin{
String autor,tytul;
Ksiazka(String x, String y){
this.autor=x;this.tytul=y;
}
public String toString(){
return (Ksiazka.id+","+autor+","+tytul);
}
}
class Czasopismo extends Wolumin{
String tytul,numerWydania;
Czasopismo(String x, String y){
tytul=x;
numerWydania=y;
}
public String toString(){
return (Czasopismo.id+","+tytul+","+numerWydania);
}
}
Your id is marked static, so all instances of Wolumin will have the same value of that variable. You need to have an additional instance variable that is unique to each instance. For example:
abstract class Wolumin{
static int id;
private final int myId;
Wolumin(){
myId = id++;
};
int getMyId() {
return myId;
}
}
And then:
class Ksiazka extends Wolumin{
String autor,tytul;
Ksiazka(String x, String y){
this.autor=x;this.tytul=y;
}
public String toString(){
return (getMyId()+","+autor+","+tytul); // use myId instead
}
}
class Czasopismo extends Wolumin{
String tytul,numerWydania;
Czasopismo(String x, String y){
tytul=x;
numerWydania=y;
}
public String toString(){
return (getMyId()+","+tytul+","+numerWydania); // use myId instead
}
}
How to fix the issue?
Re-arrange the System.out.println statements to print immediately after an object is created.
Working code:
tab[0]=new Ksiazka("Malysz","Homies");
System.out.println(tab[0].toString());
tab[1]=new Ksiazka("Pudzian","Malta");
System.out.println(tab[1].toString());
tab[2]=new Czasopismo("Bravo","420");
System.out.println(tab[2].toString());
tab[3]=new Czasopismo("Grzyby","2137");
System.out.println(tab[3].toString());
Output of the working code:
$ java First
1,Malysz,Homies
2,Pudzian,Malta
3,Bravo,420
4,Grzyby,2137
Have a look at java.util.concurrent.atomic.AtomicInteger if you need a threadsafe solution beyond QBrute's approach.
This class has the methods incrementAndGet() and getAndIncrement(), which both do what you need.

Is it possible to convert interface type to a value?

I have an interface:
public interface TestFace {
public String outThis();
}
A class with a method whose parameter is of the interface type,:
class MyClass {
public void outMeth(TestFace inMeth){
System.out.print(inMeth); //the method attempts to print the interface type
}
}
If I call the object's method like so:
MyClass a = new MyClass();
a.outMeth(new TestFace() {
public String outThis() {
String val = "something";
return val;
}
});
the printed value is a reference to the instance. Could someone explain why this happens/how to do this properly?
The result of doing System.out.println on an Object will always be the result of invoking the object's toString() method. If you inherit that from Object (by not writing an explicit toString()), you get the default Object implementation, which is specified:
The toString method for class Object 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. In other words, this method returns a string equal to the value of:
getClass().getName() + '#' + Integer.toHexString(hashCode())
The "name" of an anonymous class generally reflects the class in which the anonymous class was defined, often with $1 or the like added to the end.
If you want a more useful toString(), override it and write one yourself:
new TestFace() {
public String outie() {
String val = "something";
return val;
}
public String toString() {
return outie();
}
}
If you want to print val, just override the toString() method.
MyClass a = new MyClass();
a.outMeth(new TestFace() {
public int outie() {
int val = "something";
return val;
}
#Override
public String toString() {
return outie();
}
});

how can I return a String?

package book1;
import java.util.ArrayList;
public abstract class Book {
public String Book (String name, String ref_num, int owned_copies, int loaned_copies ){
return;
}
}
class Fiction extends Book{
public Fiction(String name, String ref_num, int owned_copies, String author) {
}
}
at the moment when i input values into the variable arguments and call them with this :
public static class BookTest {
public static void main(String[] args) {
ArrayList<Book> library = new ArrayList<Book>();
library.add(new Fiction("The Saga of An Aga","F001",3,"A.Stove"));
library.add(new Fiction("Dangerous Cliffs","F002",4,"Eileen Dover"));
for (Book b: library) System.out.println(b);
System.out.println();
}
}
i get a return value of this:
book1.Fiction#15db9742
book1.Fiction#6d06d69c
book1.NonFiction#7852e922
book1.ReferenceBook#4e25154f
how can i convert the classes to return a string value instead of the object value? I need to do this without changing BookTest class. I know i need to use to string to convert the values. but i don't know how to catch the return value with it. could someone please point me in the right direction on how to convert this output into a string value?
You need to overwrite the toString() Method of your Book class. In this class you can generate a String however you like. Example:
#Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.author).append(": ").append(this.title);
return sb.toString();
}
You need to override the toString() method in your Book or Fiction class. The method is actually declared in the Object class, which all classes inherit from.
#Override
public String toString(){
return ""; // Replace this String with the variables or String literals that you want to return and print.
}
This method is called by System.out.println() and System.out.print() when they receive an object in the parameter (as opposed to a primitive, such as int and float).
To reference the variables in the method, you'll need to declare them in the class and store them via the class's constructor.
For example:
public abstract class Book {
private String name;
private String reference;
private int ownedCopies;
private int loanedCopies;
public Book (String name, String reference, int ownedCopies, int loanedCopies) {
this.name = name;
this.reference = reference;
this.ownedCopies = ownedCopies;
this.loanedCopies = loanedCopies;
}
#Override
public String toString(){
return name + ", Ref:" + reference + ", OwnedCopies: " + ownedCopies + ", LoanedCopies: " + loanedCopies; // Replace this String with the variables or String literals that you want to return and print.
}
}
The classes you have defined, don't store any values. It is in other words useful to construct a new book. You need to provide fields:
public abstract class Book {
private String name;
private String ref_num;
private int owned_copies;
private int loaned_copies;
public String Book (String name, String ref_num, int owned_copies, int loaned_copies) {
this.name = name;
this.ref_num = ref_num;
this.owned_copies = owned_copies;
this.loaned_copies = loaned_copies;
}
public String getName () {
return name;
}
//other getters
}
Now an object is basically a set of fields. If you want to print something, you can access and print one of these fields, for instance:
for (Book b: library) System.out.println(b.getName());
In Java, you can also provide a default way to print an object by overriding the toString method:
#Override
public String toString () {
return ref_num+" "+name;
}
in the Book class.
Need to give your object Book a ToString() override.
http://www.javapractices.com/topic/TopicAction.do?Id=55
Example:
#Override public String toString()
{
return name;
}
Where name, is a string in the Class.
I am hoping that you have assigned the passed arguments to certain attributes of the classes. Now, once you are done with that, you can override the toString() method in Book to return your customized string for printing.

String s1=new String("demo"); While printing why does it give output as the given string?

If we create a String like below and print the value:
String s=new String("demo");
System.out.println(s);
...the output is:
demo
Good. This is the expected output. But here String is a class. Remember that. Below is another example. For example, take a class like this:
class A
{
public static void main (String args[])
{
A a =new A();
A a1=new A("hi"); //we should create a Constructor like A(String name)
System.out.println(a1); //here O/P is address
}
}
My doubt is that I created the A instance in the same way I created the new String object, and I printed that object. So why does it not print the given String for the instance of A?
You need to override the Object#toString() in your class. By default, the toString() method of Object is called.
Also, to print the value, you just need to override the method as internally a call will be made to the toString() method when this statement is executed.
System.out.println(a1);
Sample overriden toString() method.
#Override
public String toString() {
// return a string value
return "The String representation of your class, as per your needs";
}
You have to override toString() method in your class the way you want to print something when call System.out.println();. In String class toString() method has override and you will get out put above due to that.
As pointed out already, you need to override the default toString() method inherited from the Object class. Every class automatically extends the Object class, which has a rather simple toString(), which can't know how to turn your particular object into a String. Why should it, especially if your class is arbitrarily complex? How is it supposed to know how to turn all your class's fields into a "sensible" string representation?
In the toString() of your class, you need to return the string that you want to represent your class with. Here is a simple example:
class A {
String foo;
public A(String foo) {
this.foo = foo;
}
public String toString() {
return foo;
}
}
public class sample {
public static void main(String[] args) {
A a = new A("Hello world!");
System.out.println(a);
}
}
String is a class whose purpose is to hold a string value and will return that value if referenced. When you use other classes, you will usually want to add other behavior. If you want to use the class to hold different values that you can set (on object creation or later in processing) you may want to use "setter" and "getter" methods for such values.
Here is an example:
public class Snippet {
private static final String C_DEFAULT_VALUE = "<default value>";
private String name;
private static Snippet mySnippet;
public Snippet() {
}
public Snippet(String value) {
setName(value);
}
/**
* #param args
*/
public static void main(String[] args) {
if (args != null && args.length > 0) {
mySnippet = new Snippet(args[0]);
} else {
mySnippet = new Snippet(C_DEFAULT_VALUE);
}
System.out.println(mySnippet.getName());
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}

what's wrong with my class definition?

Why won't this class compile?
class Exam {
private int score;
// constructor initializes score to 99
public void Exam() {
score = 99;
}
// returns the current value of score
private int getScore() {
return score;
}
// returns the String representation of the Object
public String toString() {
return "The score is " + getScore();
}
}
Your constructor shouldn't have a return type. Not even void.
public Exam() {
score = 99;
}
A construct should not contain the void keyword:
public Exam() {
score = 99;
}
A constructor returns a reference the the newly created object. But you don't have to write it. So thinking it is void is wrong as well.
Constructors don't need return types. Remove void and you should be set.
In a constructor you don't use void.
Write the constructor as:
public Exam() {
score = 99;
}
The main problem is the missing package declaration.
package yourpkg;
class Exam {
Additionally, the return type on the for Exam() makes it a function instead of a constructor and will result in a warning.
Just a suggestion not related to the concrete problem:
private int score;
// returns the current value of score
private int getScore() {
return score;
}
There is no point in having that getScore() if your going to keep it private. Make it public.
Also, always use the #Override annotation whenever your intention is to override some method. Compiler will let you known in case you are failing to do so. That means bug prevention.
e.g.
// returns the String representation of the Object
#Override
public String toString() {
return "The score is " + getScore();
}

Categories

Resources