How to convert object value into string containing multiple data in objects? - java

class Author
{
String name;
String email;
char gender;
Author(String name,String email,char gender)
{
this.name = name;
this.email = email;
this.gender = gender;
}
}
class Book
{
String name;
Author author;
double price;
int qtyInStock;
Book(String name,Author author,double price,int qtyInStock)
{
this.name = name;
this.author = author;
this.price = price;
this.qtyInStock = qtyInStock;
}
void setName(String name)
{
this.name = name;
}
void setAuthor(Author author)
{
this.author = author;
}
void setPrice(double price)
{
this.price = price;
}
void setQtyInStock(int qtyInStock)
{
this.qtyInStock = qtyInStock;
}
String getName()
{
return name;
}
Author getAuthor()
{
return author;
}
double getPrice()
{
return price;
}
int getQtyInStock()
{
return qtyInStock;
}
}
public class HOA1
{
public static void main(String[] args)
{
Author author = new Author("Javed","javedansarirnc#gmail.com",'M');
Book book = new Book("WiproS",author,500.99,3);
book.setName("JavaWorld");
System.out.println(book.getName());
String[] authDetails = book.getAuthor().toString();
for(String strr: authDetails)
{
System.out.println(strr);
}
}
}
In the above code, I have to provide solution for the question stated as "Create a class Author with the following information.
Member variables : name (String), email (String), and gender (char)
Parameterized Constructor: To initialize the variables
Create a class Book with the following information.
Member variables : name (String), author (of the class Author you have just created), price (double), and qtyInStock (int)
[Assumption: Each book will be written by exactly one Author]
Parameterized Constructor: To initialize the variables
Getters and Setters for all the member variables
In the main method, create a book object and print all details of the book (including the author details) "
I am not able to solve it !
I want to print author details using book object .Please help.

First, you need to override the toString() method in your Author class, to pretty print the fields. An example could be:
class Author {
// ... your fields ...
#Override
public String toString() {
return "Author{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
'}';
}
}
Then, here's the mistake that you are making.
The toString() method from the Author class returns a String, not an array of String (String[] as you did). So, you could just do:
String authDetails = book.getAuthor().toString();
System.out.println(authDetails);
But, the recommended way to do this is the following. Just use an object for the Author class, and pass that object to the System.out.println(...) method. This will automatically call the toString() method on the given object.
Author author = book.getAuthor();
System.out.println(author);
Has the same effect as:
System.out.println(author.toString());

Override the toString() method in your Author class. See below the code
class Author {
// ... your fields ...
#Override
public String toString() {
return "Author{" +
"name='" + name + '\'' +
", email='" + email + '\'' +
", gender=" + gender +
'}';
}
Once toString method is defined in Author class you can print the Author class all objects data using either toString method or when you print the Author instance as well.
System.out.println("Author data:"+book.getAuthor());
The toString() method returns the string representation of the object. If you print any object, java compiler internally invokes the toString() method on the object. So overriding the toString() method, returns the desired output, it can be the state of an object etc.

Related

The field is not visible JAVA

I'm currently working on a program, and in my subclass, I need to have a no argument constructor that initializes the object with empty strings.
I've tried using super, I have setter and getter methods, but I keep getting "the field Person.name is not visible". I get this for address and phoneNumber as well.
How do I make it so it is visible, and I can initialize the objects without giving the constructor arguments? Please let me know if I'm doing anything wrong and need to fix something (:
// Create a class named Person
public class Person {
// Fields: name, address, and phone number. (2 points)
private String name;
private String address;
private String phoneNumber;
// No argument constructor that initializes the object with empty strings for name, address, and phone. (2 points)
public Person () {
super();
this.name = "";
this.address = "";
this.phoneNumber = "";
}
// 3 argument constructor that initializes the object with a name, address, and a phone number. (2 points)
public Person2 (String name, String address, String phoneNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}
// Getter/setter methods for each of the fields. (3 points)
// set/get name
public void setName (String name) {
this.name = name;
}
public String getName () {
return this.name;
}
// set/get address
public void setAddress (String address) {
this.address = address;
}
public String getAddress () {
return this.address;
}
// set/get phone number
public void setPhoneNumber (String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber () {
return this.phoneNumber;
}
// toString method that returns a string for the name, address, and phone number (2 points)
// (you can override the toString method as part of a class which is pretty swag)
public String toString() {
return "Name: " + name + "\n" + "Address: " + address + "\n" + "Phone: " + phoneNumber;
}
}
// Create a subclass of Person named Customer
class Customer extends Person {
// A field for a customer number. (1 point)
private String customerNumber;
public Customer () {
// A no argument constructor that initializes the object with an empty string for the name, address, phone, and customer number. (2 points)
super(name, address, phoneNumber);
}
// A 4 argument constructor that initializes the object with a name, address, a phone number, and a customer number. (2 points)
public Customer2 (String name, String address, String phoneNumber, String customerNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
this.customerNumber = customerNumber;
}
// Getter/setter method for the customer number field. (1 point)
public void setCustomerNumber (String customerNumber) {
this.customerNumber = customerNumber;
}
// toString method that prints the information from the Person toString as well as the customer number (2 points)
public String toString() {
return "Name: " + name + "\n" + "Address: " + address + "\n" + "Phone: " + phoneNumber + "\n" + "Customer Number: " + customerNumber;
}
}
If a field is marked with private access then it can only be accessed from inside that class or instances of it. You should use the get methods. Or, you can get the result of toString and build on that.
Also, all constructors should have the same name as the class (no "2" added).
public class Person {
private String name;
private String address;
private String phoneNumber;
public Person() {
this("", "", "");
}
public Person(String name, String address, String phoneNumber) {
this.name = name;
this.address = address;
this.phoneNumber = phoneNumber;
}
public void setName (String name) {
this.name = name;
}
public String getName () {
return this.name;
}
public void setAddress (String address) {
this.address = address;
}
public String getAddress () {
return this.address;
}
public void setPhoneNumber (String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getPhoneNumber () {
return this.phoneNumber;
}
#Override
public String toString() {
return "Name: " + name + "\n" + "Address: " + address + "\n" + "Phone: " + phoneNumber;
}
}
// Create a subclass of Person named Customer
class Customer extends Person {
private String customerNumber;
public Customer () {
this("", "", "", "");
}
public Customer (String name, String address, String phoneNumber, String customerNumber) {
super(name, address, phoneNumber);
this.customerNumber = customerNumber;
}
public String getCustomerNumber() {
return customerNumber;
}
public void setCustomerNumber (String customerNumber) {
this.customerNumber = customerNumber;
}
#Override
public String toString() {
return super.toString() + "\n" + "Customer Number: " + customerNumber;
}
}
You cannot access or assign to a private field in any other class than the one that it is declared in.
You cannot declare a constructor with any name other than the name of the class. Thus Person2 and Customer2 are not neither valid constructors or valid methods. (A method requires a return type!)
A constructor must explicitly (via a super call) or implicitly chain a no-args constructor in its superclass.
Basically, your choices for initializing a private field in a superclass are either use a super(...) call to chain the a superclass constructor passing the value OR call a superclass setter method within the subclass constructor.
For example, the 4 arg constructor in Customer could be:
public Customer (String name, String address,
String phoneNumber, String customerNumber) {
super(name, address, phoneNumber);
this.customerNumber = customerNumber;
}
or
public Customer (String name, String address,
String phoneNumber, String customerNumber) {
super(); // you could leave this out - it is implied
setName(name);
setAddress(address);
setPhoneNumber(phoneNumber);
this.customerNumber = customerNumber;
}
IMO, the former is better. It is more concise and more readable.
The toString() method in Customer cannot refer directly to the private fields of the Person. It could use the fields' getters.
I don't think there is any actual need to call the super constructor in the person class. However, in the constructor for the costumer class, you should just call the super constructor with no arguments.
Edit: or you could initiate the values directly upon declaration, like the guy above me said.
PS. kinda unrelated, but, you could have one constructor but give the arguments default values. So you can call it with and without arguments with no need to override it.
There are a few issues in the snippet that you provided:
There is no need to define different names for constructors of the same class. The fact that their signature (i.e. set of input parameters) is different suffices.
Regarding your question, the error is that you're trying to access Person's private fields in the Customer's constructors directly. There are two ways to fix this issue:
Change the Person fields' scope from private to protected. This will allow any class that inherits the Person class to access the aforementioned fields directly.
When in Customer class, use the getter/setter methods to access the private fields.

how to store object in array where i want to declare 2 or more object and how to call that array using anther class object

this is main method
public static void main(String[] args) {
Author[] authors=new Author[2];
for(int i=0;i<=authors.length;i++);
authors[0]=new Author("suru","suru#qwe.com","m");
authors[1]=new Author("aksh","aksh#qwe.com","m");
for(int i=0;i<=authors.length;i++);
System.out.println(authors);
Book book=new Book("java",authors,200,2);
System.out.println(book);
now i created 2nd class authoer with getter and setter
private String name;
private String email;
private String gender;
public Author (String name,String email, String gender)
{
this.name=name;
this.email=email;
this.gender=gender;
}
noow i created new class Book
public class Book {
private String name;
private Author[] author;
private double price;
private int qty=0;
public Book(String name,Author[] author,double price, int qty) {
this.name=name;
this.author=author;
this.price=price;
this.qty=qty;
}
when i run this program the output give the memory adress ho can i print theese detail
You need to override toString() method in the class Author.
For example:
#Override
public String toString() {
return "Author [name=" + name + ", email=" + email + ", gender=" + gender + "]";
}
When you pass as argument of the method System.out.println() name of variable, method toString() of the class of that variable is being called. If you don't override that method in class Author or Book, toString() method inherited by these classes from Object class is being called (all classes in Java inherit from Object class). By default, this method prints address in memory for classes with toString() not defined in their bodies. There is a simple example, how you can override it in Author method:
class Author {
#Override
public String toString() {
return "Author name: " + this.name + "\nAuthor email: " + this.email + "\nAuthor gender : " + this.gender;
}
To print contents of an array (in your example to print each Author contained in Author[] authors) you might want to use one of these way to achieve that (as Author[] or Book[] is actually a type of array and not a type of Book or Author and has its own toString() method printing address in memory) :
Create a loop iterating over each element of authors array:
for (Author author : authors) {
System.out.println(author + "------"); // toString() method of each Author is called and added simple separator
}
Call Arrays.toString(authors) method. Class Arrays is provided to let you manipulate arrays in many different ways. You can read about this class in Java API documentation. This is a part of what documentation says about Arrays.toString() method:
Returns a string representation of the contents of the specified array. If the array contains other arrays as elements, they are converted to strings by the Object.toString() method inherited from Object, which describes their identities rather than their contents.
package oops;
public class Main {
public static void main(String[] args) {
Author[] authors=new Author[2];
for(int i=0;i<=authors.length;i++);
authors[0]=new Author("suru","suru#qwe.com","m");
authors[1]=new Author("aksh","aksh#qwe.com","m");
for(int i=0;i<=authors.length;i++);
System.out.println(authors);
Book book=new Book("java",authors,200,2);
System.out.println(book);
}
}
package oops;
public class Author {
private String name;
private String email;
private String gender;
public Author (String name,String email, String gender)
{
this.name=name;
this.email=email;
this.gender=gender;
}
public String getName() {
return name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String toString() {
return name+ " " +email+ " " +gender+ " ";
}
package oops;
public class Book {
private String name;
private Author[] author;
private double price;
private int qty=0;
public Book(String name,Author[] author,double price, int qty) {
this.name=name;
this.author=author;
this.price=price;
this.qty=qty;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public int getQty() {
return qty;
}
public void setQty(int qty) {
this.qty = qty;
}
public String getName() {
return name;
}
/*public Author[] getAuthor() {
return author;
} */
public Author[] getAuther() {
for (int i=0;i<=author.length;i++);
return author;
}
public String toString() {
return name+" "+author+" "+price+" "+qty+" ";
}
public Author[] getAutherNames() {
for (int i=0;i<=author.length;i++);
return author;
}
}
this is my full program
You an override toString() or you can print the attributes of the object directly as follows:
Book b = new Book(/*args*/);
System.out.println("Name: " + b.name);
// continue printing all the attributes in the same way
You can try this instead of overriding toString() method in the object class.
Hope this helps...

Store String of one class into an object of another class

I am working on a project that links books to their authors.The author info is part of the book class and it is an Author object in the book class and its data will become part of the book class. I have the author class:
public class Author {
private String Name;
private String email;
private char gender;
public Author( ) {
Name="Emily";
email="email#email.com";
gender='f';
}
public String getName (){
return Name;
}
public void setName (String Name){
this.Name=Name;
}
public String getEmail (){
return email;
}
public void setEmail(String email){
this.email=email;
}
public char getGender (){
return gender;
}
public void setGender(char gender){
this.gender=gender;
}
public String toString () {
String x = "Name: " + Name + "email " + "gender: " + gender;
return x;
}
}
and the book class:
public class Book {
private String name;
private Author author;
private double price;
private int quantity;
public Book (){
name="Book Name";
author=Author.toString();
price=11.79;
quantity=2;
}
public String getName(){
return name;
}
public void setName(String name){
this.name=name;
}
public Author getAuthor(){
return author;
}
public void setAuthor () {
this.author=author;
}
public double getPrice () {
return price;
}
public void setPrice (double price) {
this.price=price;
}
public int getQuantity() {
return quantity;
}
public void setQuantity (int quantity) {
this.quantity=quantity;
}
public String toString (){
String x = "Book is " + name + "Author and author info "+ author + "Price " + price + "Quantity " + quantity;
return x;
}
}
I need to store the contents of the toString() method in the Author variable in the book class as the author info. How do I do this?
You don't need to store the value of the toString() method of the Author class, this would couple your classes unnecessarily and break one of the core principals of good OO design.
The toString method of the Author class should be responsible for presenting a sensible String representation of its state (which it seems to). Your book class should do the same, delegating to classes it interacts with to do the same:
public String toString() {
return "Book is " + name + "Author and author info "+ author.toString() + "Price " + price + "Quantity " + quantity;
}
As noted in the comments, you're already doing this in the code snippet posted in the question, your question implies that this this may have not been 'by design'. I would recommend researching Object Encapsulation and delegation.

How make toString() method return Super Class private fields also along with its instance fields?

Is there a way to make toString() include private fields of the super class? I tried adding a super.toString(), no use however.
Please see the code below
Employee.java
package test;
public class Employee {
private String name;
private int id;
private double salary;
public Employee(String name, int id, double salary) {
super();
this.name = name;
this.id = id;
this.salary = salary;
}
public double getSalary() {
return salary;
}
#Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + ", salary=" + salary
+ "]";
}
public static void main(String[] args) {
Employee e=new Employee("Joe", 14, 5000);
System.out.println(e);
Manager m=new Manager("Bill", 23, 5000, 10);
System.out.println(m);
System.out.println("Employee Salary is "+e.getSalary()+"\nManager salary is "+m.getSalary());
}
}
Manager.java
package test;
public class Manager extends Employee{
private double bonus;
public Manager(String name, int id, double salary,int bonus) {
super(name, id, salary);
this.bonus=bonus;
}
public double getSalary()
{
double baseSalary=super.getSalary();
return (baseSalary+baseSalary*(bonus/100));
}
#Override
public String toString() {
return(this.getClass().getName()+" ["+super.toString().substring((this.getClass().getSuperclass().getName().length()-3
), (super.toString().length())-1)+", bonus="+bonus+"]");
//didn't work
//super.toString();
//return "Manager [bonus=" + bonus + "]";
}
}
Output
Employee [name=Joe, id=14, salary=5000.0]
test.Manager [name=Bill, id=23, salary=5000.0, bonus=10.0]
Employee Salary is 5000.0
Manager salary is 5500.0
That was the best i could do , to concatenate super.toString()+' a set of Strings', surely this is messy , is there some other way , even if the language spec does not allow it does eclipse have some facility to do that , NOTE: I used eclipse to generate the toString method , any way by which i can tell eclipse to include the super class fields too,
In other words can i replace this messy code
return(this.getClass().getName()+" ["+super.toString().substring((this.getClass().getSuperclass().getName().length()-3
), (super.toString().length())-1)+", bonus="+bonus+"]");
by getting eclipse to automate the process and generate a suitable way to do it?
If you create getters and setters in your superclass then you can acces the variables through those methods. Other possibility is to change the visibility from private to protected
first solution looks like this
Employee
public class Employee {
private String name;
private int id;
private double salary;
public Employee(String name, int id, double salary) {
super();
this.name = name;
this.id = id;
this.salary = salary;
}
public double getSalary() {
return salary;
}
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 void setSalary(double salary) {
this.salary = salary;
}
#Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + ", salary=" + salary + "]";
}
}
Manager
public class Manager extends Employee {
private double bonus;
public Manager(String name, int id, double salary, int bonus) {
super(name, id, salary);
this.bonus = bonus;
}
public double getSalary() {
double baseSalary = super.getSalary();
return (baseSalary + baseSalary * (bonus / 100));
}
#Override
public String toString() {
return "Manager [name=" + getName() + ", id=" + getId() + ", salary=" + getSalary() + ", bonus=" + bonus + "]";
}
}
Second one (using protected)
Employee
public class Employee {
protected String name;
protected int id;
protected double salary;
public Employee(String name, int id, double salary) {
super();
this.name = name;
this.id = id;
this.salary = salary;
}
public double getSalary() {
return salary;
}
#Override
public String toString() {
return "Employee [name=" + name + ", id=" + id + ", salary=" + salary + "]";
}
}
Manager
public class Manager extends Employee {
protected double bonus;
public Manager(String name, int id, double salary, int bonus) {
super(name, id, salary);
this.bonus = bonus;
}
public double getSalary() {
double baseSalary = super.getSalary();
return (baseSalary + baseSalary * (bonus / 100));
}
#Override
public String toString() {
return "Manager [name=" + name + ", id=" + id + ", salary=" + salary + ", bonus=" + bonus + "]";
}
}
Personally i'd use the getter/setter method but it's up to you.
EDIT: Additonal to eclipse generation of toString() in eclipse.
You can't seem to generate it with getters and setter (just had a quick look, you can see some documentation here.
What I did figure out is how you can edit the Code Template used when generating the toString() so it includes the toString() from the superclass.
When you enter the generate toString() dialog there is a field 'String Format' with <Default Template> next to it. when you click the edit button you can create a new Code Template.
This template automatically holds the <Default Template> and should look something like this:
${object.className} [${member.name()}=${member.value}, ${otherMembers}]
only thing you'll have to add is the following at the end
[super: ${object.superToString}]
This way it'll display the toString() form the superclass
You can let eclipse generate it, however it would not look like you want it.
which creates this code:
public String toString() {
return "Manager [bonus=" + bonus + ", toString()=" + super.toString() + "]";
}
which would print this:
Manager [bonus=10.0, toString()=Employee [name=Bill, id=23, salary=5000.0]]
That's the most you can make eclipse generate for you.
You can clean it up a little so it would look like this
public String toString() {
return "Manager [bonus=" + bonus + "] is a " + super.toString();
}
which would print
Manager [bonus=10.0] is a Employee [name=Bill, id=23, salary=5000.0]
However, your custom solution works as well. So why not use it?
You can clean it up a little like this:
#Override
public String toString() {
return "Manager [" + superFieldsFromToString() + ", bonus=" + bonus + "]";
}
private String superFieldsFromToString() {
String superToString = super.toString();
int superClassNameLength = getClass().getSuperclass().getSimpleName().length();
int fieldStartIdx = superClassNameLength + 2; // + 2 removes " ["
int fieldEndIdx = superToString.length() - 1; // - 1 removes "]"
return superToString.substring(fieldStartIdx , fieldEndIdx);
}
which outputs
Manager [name=Bill, id=23, salary=5000.0, bonus=10.0]
The only other options, as others have mentioned, are to use reflection to access the private fields, make the fields protected or create public getters.
I would not advice to do any of this, as your class design should not be defined by debug output.
No.
Because if you could directly access private fields of super class, those fields would not be private.
There is something that doesn't make sense:
All your fields are either primitives and immutable thus you can safely publish (For Concurenecy purposes) them using getters.
If you have in mind making salary, id, bonus private because these should not be known(and thus not provide getters), then why provide a toString that shows this secrete information. If the toString is just for visual testing purposes, then consider making them protected and then put them private again when you have successfully tested your class.
Otherwise, there is something wrong in the structure of your classes and you are just trying to do some hacks in the language.
The possible solution is to make a protected getters for fields in case you don't want to make fields itself protected.
Best Solution
You can call the getters for the super class instance variables and put the values on your toString(). You could even be sneaky and make the getters protected so that only the child classes can view the variable's value.
Lazy Solution
Make the fields protected which might be a bad idea depending on how your super class is designed.
Bad Idea
You could also use reflection, but I wouldn't do that.
Reflection was created for a specific purpose, to discover the
functionality of a class that was unknown at compile time, similar to
what the dlopen and dlsym functions do in C. Any use outside of that
should be heavily scrutinized. (https://softwareengineering.stackexchange.com/questions/193526/is-it-a-bad-habit-to-overuse-reflection)
If you can't change the code of the super class (change scope of members or add a getter), then you can use the Java reflection API to access a private field:
Manager managerObject = new managerObject():
Employee e = (Employee) managerObject;
Field f = e.getClass().getDeclaredField("salary");
f.setAccessible(true);
double sal = (double) f.get(e);

Creating a class with different argument lengths

How do I create a class that has different lengths of arguments?
public static void main(String[] args) {
group g1 = new group("Redskins");
group g2 = new group("Zack", "Mills", 21);
group g3 = new group("John","Smith",20);
group g4 = new group("Fred","Fonsi",44);
group g5 = new group("Jeb","Bush",26);
System.out.println(g1.getName());
}
}
I want to be able to display the team name (redskins) and then each member after that using one method.
I've tried using two methods and got that to work, but can't get one.
I was thinking about possibly using an array but not sure if that would work.
Thanks for any help.
I have three classes the main, student, and group.
I need the group class to display the group name and then figure out how to display the students information underneath. The only thing, is that my assignment is vague about whether I can use two methods or one.
public class student {
String firstName;
String lastName;
int age;
student(String informedFirstName, String informedLastName, int informedAge){
firstName = informedFirstName;
lastName = informedLastName;
age = informedAge;
}
String getName()
{
return "Name = " + firstName + " " + lastName + ", " + "Age = " + age;
}
}
public class Team{
String name;
Set<Player> players;
public Team(String name){
this.name = name;
}
public void addPlayer(Player p){
players.add(p);
}
}
public class Player{
String name;
etc
}
EDIT for revised question:
Ok, Im going to show a lot here. Heres what a proper Java versio of what you want for student.
public class Student {
private String firstName;
private String lastName;
private int age;
public Student(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
/*
* Use:
* Student s = new Student(Bill, Nye, 57);
* System.out.println(s.toString());
*/
#Override
public String toString() {
return "First Name: " + firstName + ", Last Name: " + lastName + ", Age: " + age;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
The Things to take away from this.
1) Capitalize the first letter of class names! (Student)
2) note the class variables are private (look here for a tutorial Java Class Accessibility) and have getters and setter to control access outside the class.
3) I dont say "getName()" and return name and age. This doesnt make sense. Instead i make it so when you go toString() it shows all the relevant information.
4) Java is an object oriented language which means the classes that model data are supposed (to some extent) model appropriately to the way they are used in real life. This makes it more intuitive to people reading your code.
5) if your Group class (note the capital!) needs to contain many Students use a LIST such as an ArrayList. Arrays would make no sense because you dont know how many Students are going to be in each Group. A SET like i used above is similar to a list but only allows ONE of each item. For simplicity use a list though
6) the THIS operator refers to class (object) variables. In the constructor this.firstName refers to the firstName within the Class (object...an instance of the class) whereas just firstName would refer to the variable in the contructor and not alter the class variable.
use the constructor for that
class group {
String fname,lname;
group(String fname ){
this.fname=fname;
}
group(String fname,String lname){
this.fname=fname;
this.lname=lname;
}
group(String fname,String lname,int age){
this.fname=fname;
this.lname=lname;
this.age=age;
}
public String getName(){
return fname+lname+age;
}
}

Categories

Resources