public class OOP_10_Encapsulation {
private String firstName;
private String favFood;
private int age;
private float weight;
//create a set method for firstName
public void setFirstName(String firstName){
this.firstName = firstName;
}
//create a get method for firstName
public String getFirstName(String firstName){
this.firstName = firstName;
return firstName;
}
//create a set method for favFood
public void setFavFood(String favFood){
this.favFood = favFood;
}
//create get method for favFood
public String getFavFood(String favFood){
this.favFood = favFood;
return favFood;
}
//create a set method for age
public void setAge(int age){
this.age = age;
}
//create a get method for age
public int getAge(int age){
this.age = age;
return age;
}
//create a set method for weight
public void setWeight(float weight){
this.weight = weight;
}
//create a get method for weight
public float getWeight(float weight){
this.weight = weight;
return weight;
}
}
public class OOP_11_TestEncapsulation {
public static void main(String[] args) {
OOP_10_Encapsulation learner1 = new OOP_10_Encapsulation(); //create object of OOP_10_Encapsulation
learner1.setFirstName("Evander O A");
learner1.setAge(31);
learner1.setWeight(98.6F);
learner1.setFavFood("waakye");
System.out.println("Hi, my name is " + learner1.getFirstName());
}
}
I have this challenge that I am not able to get my head around. When I run the code in the main method, the get method does not return the name "Evander O A" as set in the set method. Actually, none of my get methods are getting anything I need them to get.
Let's look at one of your get methods:
//create a get method for age
public int getAge(int age){
this.age = age;
return age;
}
The purpose of a get method, also called "getter" is to get something from inside an object, usually it's some of the object's attribute that you wanna get.
If you just want to get an attribute, there is no need to pass a parameter to the get method:
public int getAge(int age) // age parameter is useless
Not only that it is useless here, but you are also doing something wrong, in the get method you are first changing attribute's value. You are effectively doing a set inside a getter method:
this.age = age; // wrong
Given your code for getAge method, let's see how it will execute when you call something like:
System.out.println("Hi, my name is " + learner1.getAge())
The function getAge will be called with no parameter, although it is expecting one. So most probably you won't be able to compile this piece of code.
I got the following error when trying to compile something similar:
https://imgur.com/a/4AVwMke
So if you create a function with 1, 2, 3 or whatever number of parameters then you must call it using the same number of arguments to the function call. Otherwise most probably that code won't run.
Now let's assume I call it with some value as argument, probably you did too.
System.out.println("Hi, my name is " + learner1.getAge(0))
This is going to happen:
//create a get method for age
public int getAge(int age // which is 0){
this.age = age; // you set the age to 0, losing the old value
return age; // you return 0, because you no longer have the old value
}
How should you do it? Simple:
//create a get method for age
public int getAge(){
return age;
}
Now apply this fix to all of your getters (the get methods) and you are good to go. Let me know if something is not clear.
This is for a school project. I have built a simple class with 3 string variables and a constructor to fill these fields.
public class Names {
String firstName;
String middleName;
String lastName;
public Names(String name){
System.out.println("Passed name is: " + name);
}
public void setFirstName(String name){
firstName = name;
}
public void setMiddleName(String name){
middleName = name;
}
public void setLastName(String name){
lastName = name;
}
public static void main(String []args){
Names drew = new Names("Drew");
drew.setFirstName("Drew");
drew.setMiddleName("Leland");
drew.setLastName("Sommer");
System.out.println(drew.firstName + " " + drew.middleName + " " + drew.lastName);
}
public getFirstName(String name){
}
public getMiddleName(String name){
}
public getLastName(String name){
}}
At the bottom where it is getFirstName, getMiddleName, getLastName I want to be able to pass something like getFirstName(drew) and have it return drew.firstName?
I am very new to java FYI.
These are "getter" methods to return the values of instance fields. drew is your current Names instance here, therefore if you call these methods on this instance, you'll receive the values you've set with your "setter" methods. And since you're calling them on a specific instance, you don't need to pass it as a method argument. That is why these getter methods are normally parameterless.
They should look like this:
public String getFirstName() {
return firstName;
}
public String getMiddleName() {
return middleName;
}
public String getLastName() {
return lastName;
}
Please note that I've added the corresponding return type (String), because the data type of each instance field is String.
Your println call in the main method would then look like this:
System.out.println(drew.getFirstName() + " " + drew.getMiddleName() + " " + drew.getLastName());
public String getFirstName() {
return this.firstName;
}
This will return the firstName of the object you call it on.
You can call it like this:
System.out.println(drew.getFirstName() + " " + drew.middleName + " " + drew.lastName);
You can then do the same thing for getMiddleName and getLastName.
Your get methods will be called by an instance of your Names class. When you create an instance of the class and assign it a variable name, just use that variable name to call the method and it will return the name for that instance.
//Instantiate the Names class
Names drew = new Names("Drew");
//Call methods to set the names
drew.setFirstName("Drew");
drew.setMiddleName("John");
drew.setLastName("Smith");
//Call methods to get the names
drew.getFirstName(); //Returns "Drew"
drew.getMiddleName(); //Returns "John"
drew.getLastName(); //Returns "Smith"
And, like others suggested, your get / set methods should be like this:
public void setFirstName(String n){
firstName = n;
}
public String getFirstName(){
return firstName;
}
as you said, "I want to be able to pass something like getFirstName(drew) and have it return drew.firstName"
so the impl is simple,
public String getFirstName(Names other) {
return other.firstName;
}
This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed last month.
I do not understand why my output is not what I expected, instead of showing the persons information, the output displays: examples.Examples#15db9742
Am I doing something wrong in my code?
package examples;
public class Examples {
String name;
int age;
char gender;
public Examples(String name, int age, char gender){
this.name = name;
this.age = age;
this.gender = gender;
}
public static void main(String[] args) {
Examples[] person = new Examples[10];
person[0] = new Examples("Doe",25,'m');
System.out.println(person[0]);
}
}
Add a toString() method to your class:
public class Examples {
String name;
int age;
char gender;
public Examples(String name, int age, char gender){
this.name = name;
this.age = age;
this.gender = gender;
}
#Override
public String toString() {
StringBuilder result = new StringBuilder();
result.append(this.name + " ");
result.append(this.age + " ");
result.append(this.gender + " ");
return result.toString();
}
public static void main(String[] args) {
Examples[] person = new Examples[10];
person[0] = new Examples("Doe",25,'m');
System.out.println(person[0]);
}
}
When you say
System.out.println(person[0]);
java doesn't automatically know what you want printed out. To tell it, you write a method in your Examples class called toString() which will return a string containing the info you want. Something like:
#Override
public String toString() {
return "Name: " + name +
" Age: " + String.valueOf(this.age) +
" Gender: " + String.valueOf(this.gender);
}
Java has no way of knowing what you want it to print. By default, the toString() method is called when you use System.out.println() with an object.
Your Examples class should have its own toString() method so you can decide what to print. The default toString() returns a representation of the object in memory.
For example, to print out the object's name:
package examples;
public class Examples {
...
#Override
public String toString() {
return name;
}
}
Your output is right, when you print an object the method toString() of the object is called; by default it returns what you see (the class and a memory direction).
Override the method toString() of the class to make him return a descriptive String. E.g.:
public class Examples {
// The same ...
public String toString(){
return "My name is " + name + " and I have " + age + " years."
}
// The same ...
}
If you do that you will get a more descriptive String when calling toString() and so when printing an object of class Examples.
New output is
My name is Dow and I have 25 years.
person is an array of type Examples, so by acessing person[0] you are telling it to print an Examples instance. Since the Examples class does not implement an toString() method it will call the parent Object.toString() method that produces the output you are seeing.
Add the following method to your Examples class
public String toString() {
return "[name="+this.name+", age="+this.age+", gender="+this.gender+"]";
}
You have explicitly to create a method which outputs the persons data or override the toString() method to do the same thing:
public class Person
{
String name;
int age;
char gender;
public Person(String name, int age, char gender)
{
this.name = name;
this.age = age;
this.gender = gender;
}
//Override the toString() method
//is a usual programming technique
//to output the contents of an object
public String toString()
{
return "Name: " + this.name + "\nAge: " + this.age + "\nGender: "
+ this.gender;
}
//You can also write something like this
public void showInfo()
{
System.out.printf("Persons Info:\n\nName: %s\nAge: %s\nGender: %s", this.name, this.age, this.gender);
}
public static void main(String[] args)
{
Person p = new Person("bad_alloc", 97, 'm');
//System.out.println("Persons info:\n" + p.toString());
//If you want directly to "output the object" you have to override the toString() method anyway:
//System.out.println(p);//"Outputting the object", this is possible because I have overridden the toString() method
p.showInfo();
}
}
I need to print the first name, last name, and salary from two employee objects but I keep getting a cannot find symbol error. What would I do to fix this?
Here is the constructor class:
public class Employee
{
private String firstName;
private String lastName;
private double monthlySalary;
public Employee( String firstName1, String lastName1, double monthlySalary1) {
setfirstName(firstName1);
setlastName(lastName1);
setmonthlySalary(monthlySalary1);
}
String getfirstName() {
return firstName;
}
String getlastName() {
return lastName;
}
double getmonthlySalary() {
return monthlySalary;
}
public void setfirstName (String firstName1) {
firstName = firstName1;
}
public void setlastName (String lastName1) {
lastName = lastName1;
}
public void setmonthlySalary (double monthlySalary1) {
monthlySalary = ( monthlySalary1 >= 0 ? monthlySalary1 : 0);
}
}
And here is what I have so far to print the objects:
public class EmployeeTest {
public static void main(String[] args) {
Employee a = new Employee("John", "Smith", 10000);
Employee b = new Employee("Jane", "Smith", 11000);
System.out.print(a.firstName1);
}
}
I need to be able to have it print out something along the lines of "Name: Salary:" But I am clueless as to how to make this work. Any help would be greatly appreciated.
In your employee class, you need to override the toString() method.
You can try something like:
#Override
public String toString()
{
System.out.println("Name: "+name+"Salary: "+salary);
}
Then for each of your employees, when you want to print them, just call
System.out.println(employee);
You cant print out firstName (or firstName1, because that doesnt exist in your class), because its marked as private. You should do something like this:
System.out.print(a.getfirstName())
firstName is private, which means that it cannot be seen outside of the object/class it resides in. I suggest you try overriding the toString() method on your Employee class. That method would have access to all the private members of Employee.
Alternately, you could use getfirstName() to return the first name.
Also, this may be a typo, but there is no firstName1 in Employee - it is firstName.
Can anybody explain to me the concept of the toString() method, defined in the Object class? How is it used, and what is its purpose?
From the Object.toString docs:
Returns a string representation of the
object. In general, the toString
method returns a string that
"textually represents" this object.
The result should be a concise but
informative representation that is
easy for a person to read. It is
recommended that all subclasses
override this method.
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())
Example:
String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());
output:- mystr.toString: [Ljava.lang.String;#13aaa14a
Use of the String.toString:
Whenever you require to explore the constructor called value in the String form, you can simply use String.toString...
for an example...
package pack1;
import java.util.*;
class Bank {
String n;
String add;
int an;
int bal;
int dep;
public Bank(String n, String add, int an, int bal) {
this.add = add;
this.bal = bal;
this.an = an;
this.n = n;
}
public String toString() {
return "Name of the customer.:" + this.n + ",, "
+ "Address of the customer.:" + this.add + ",, " + "A/c no..:"
+ this.an + ",, " + "Balance in A/c..:" + this.bal;
}
}
public class Demo2 {
public static void main(String[] args) {
List<Bank> l = new LinkedList<Bank>();
Bank b1 = new Bank("naseem1", "Darbhanga,bihar", 123, 1000);
Bank b2 = new Bank("naseem2", "patna,bihar", 124, 1500);
Bank b3 = new Bank("naseem3", "madhubani,bihar", 125, 1600);
Bank b4 = new Bank("naseem4", "samastipur,bihar", 126, 1700);
Bank b5 = new Bank("naseem5", "muzafferpur,bihar", 127, 1800);
l.add(b1);
l.add(b2);
l.add(b3);
l.add(b4);
l.add(b5);
Iterator<Bank> i = l.iterator();
while (i.hasNext()) {
System.out.println(i.next());
}
}
}
... copy this program into your Eclipse, and run it... you will get the ideas about String.toString...
The toString() method returns a textual representation of an object. A basic implementation is already included in java.lang.Object and so because all objects inherit from java.lang.Object it is guaranteed that every object in Java has this method.
Overriding the method is always a good idea, especially when it comes to debugging, because debuggers often show objects by the result of the toString() method. So use a meaningful implementation but use it for technical purposes. The application logic should use getters:
public class Contact {
private String firstName;
private String lastName;
public Contact (String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getContact() {
return firstName + " " + lastName;
}
#Override
public String toString() {
return "["+getContact()+"]";
}
}
It may optionally have uses within the context of an application but far more often it is used for debugging purposes. For example, when you hit a breakpoint in an IDE, it's far easier to read a meaningful toString() of objects than it is to inspect their members.
There is no set requirement for what a toString() method should do. By convention, most often it will tell you the name of the class and the value of pertinent data members. More often than not, toString() methods are auto-generated in IDEs.
Relying on particular output from a toString() method or parsing it within a program is a bad idea. Whatever you do, don't go down that route.
toString() returns a string/textual representation of the object.
Commonly used for diagnostic purposes like debugging, logging etc., the toString() method is used to read meaningful details about the object.
It is automatically invoked when the object is passed to println, print, printf, String.format(), assert or the string concatenation operator.
The default implementation of toString() in class Object returns a string consisting of the class name of this object followed by # sign and the unsigned hexadecimal representation of the hash code of this object using the following logic,
getClass().getName() + "#" + Integer.toHexString(hashCode())
For example, the following
public final class Coordinates {
private final double x;
private final double y;
public Coordinates(double x, double y) {
this.x = x;
this.y = y;
}
public static void main(String[] args) {
Coordinates coordinates = new Coordinates(1, 2);
System.out.println("Bourne's current location - " + coordinates);
}
}
prints
Bourne's current location - Coordinates#addbf1 //concise, but not really useful to the reader
Now, overriding toString() in the Coordinates class as below,
#Override
public String toString() {
return "(" + x + ", " + y + ")";
}
results in
Bourne's current location - (1.0, 2.0) //concise and informative
The usefulness of overriding toString() becomes even more when the method is invoked on collections containing references to these objects. For example, the following
public static void main(String[] args) {
Coordinates bourneLocation = new Coordinates(90, 0);
Coordinates bondLocation = new Coordinates(45, 90);
Map<String, Coordinates> locations = new HashMap<String, Coordinates>();
locations.put("Jason Bourne", bourneLocation);
locations.put("James Bond", bondLocation);
System.out.println(locations);
}
prints
{James Bond=(45.0, 90.0), Jason Bourne=(90.0, 0.0)}
instead of this,
{James Bond=Coordinates#addbf1, Jason Bourne=Coordinates#42e816}
Few implementation pointers,
You should almost always override the toString() method. One of the cases where the override wouldn't be required is utility classes that group static utility methods, in the manner of java.util.Math. The case of override being not required is pretty intuitive; almost always you would know.
The string returned should be concise and informative, ideally self-explanatory.
At least, the fields used to establish equivalence between two different objects i.e. the fields used in the equals() method implementation should be spit out by the toString() method.
Provide accessors/getters for all of the instance fields that are contained in the string returned. For example, in the Coordinates class,
public double getX() {
return x;
}
public double getY() {
return y;
}
A comprehensive coverage of the toString() method is in Item 10 of the book, Effective Java™, Second Edition, By Josh Bloch.
Whenever you access an Object (not being a String) in a String context then the toString() is called under the covers by the compiler.
This is why
Map map = new HashMap();
System.out.println("map=" + map);
works, and by overriding the standard toString() from Object in your own classes, you can make your objects useful in String contexts too.
(and consider it a black box! Never, ever use the contents for anything else than presenting to a human)
Correctly overridden toString method can help in logging and debugging of Java.
Coding:
public class Test {
public static void main(String args[]) {
ArrayList<Student> a = new ArrayList<Student>();
a.add(new Student("Steve", 12, "Daniel"));
a.add(new Student("Sachin", 10, "Tendulkar"));
System.out.println(a);
display(a);
}
static void display(ArrayList<Student> stu) {
stu.add(new Student("Yuvi", 12, "Bhajji"));
System.out.println(stu);
}
}
Student.java:
public class Student {
public String name;
public int id;
public String email;
Student() {
}
Student(String name, int id, String email) {
this.name = name;
this.id = id;
this.email = email;
}
public String toString(){ //using these toString to avoid the output like this [com.steve.test.Student#6e1408, com.steve.test.Student#e53108]
return name+" "+id+" "+email;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public int getId(){
return id;
}
public void setId(int id){
this.id=id;
}
public String getEmail(){
return email;
}
public void setEmail(String email){
this.email=email;
}
}
Output:
[Steve 12 Daniel, Sachin 10 Tendulkar]
[Steve 12 Daniel, Sachin 10 Tendulkar, Yuvi 12 Bhajji]
If you are not used toString() in Pojo(Student.java) class,you will get an output like [com.steve.test.Student#6e1408, com.steve.test.Student#e53108].To avoid these kind of issue we are using toString() method.
Apart from what cletus answered with regards to debugging, it is used whenever you output an object, like when you use
System.out.println(myObject);
or
System.out.println("text " + myObject);
The main purpose of toString is to generate a String representation of an object, means the return value is always a String. In most cases this simply is the object's class and package name, but on some cases like StringBuilder you will got actually a String-text.
/**
* This toString-Method works for every Class, where you want to display all the fields and its values
*/
public String toString() {
StringBuffer sb = new StringBuffer();
Field[] fields = getClass().getDeclaredFields(); //Get all fields incl. private ones
for (Field field : fields){
try {
field.setAccessible(true);
String key=field.getName();
String value;
try{
value = (String) field.get(this);
} catch (ClassCastException e){
value="";
}
sb.append(key).append(": ").append(value).append("\n");
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
return sb.toString();
}
If you learn Python first and then Java. I think it plays the same role as __str__() method in Python, it is a magic method like __dict__() and __init__() but to refer to a string representing the the object.
the toString() converts the specified object to a string value.