Using toString() method from child class - java

Hi I am writing a code using polymorphism and I would like to print List on the screen but when I am using my code it run toString method from parent class only. How can I fix it?
public class HospitalApp {
public static void main(String[] main){
Hospital hospital = new Hospital();
List<Person> lista = new ArrayList<>();
lista = hospital.showList();
StringBuilder stringBuilder = new StringBuilder();
for(Person person : lista){
stringBuilder.append(person);
stringBuilder.append("\n");
}
System.out.println(stringBuilder.toString());
}
}
public class Hospital{
List<Person> lista = new ArrayList<>();
Person doktor = new Doctor("All", "Bundy",100, 99999);
Person nurse = new Nurse("Iga", "Lis",160, 10);
Person nurse_1 = new Nurse("Magda", "Andrych",160, 20);
public List showList(){
lista.add(doktor);
lista.add(nurse);
lista.add(nurse_1);
return lista;
}
}
public class Person{
private String imie;
private String nazwisko;
private double wyplata;
public Person(){}
public Person(String imie, String nazwisko, double wyplata){
this.imie = imie;
this.nazwisko = nazwisko;
this.wyplata = wyplata;
}
public void setImie(String imie){
this.imie = imie;
}
public String getImie(){
return imie;
}
public void setNazwisko(String nazwisko){
this.nazwisko = nazwisko;
}
public String getNazwisko(){
return nazwisko;
}
public void setWyplata(double wyplata){
this.wyplata = wyplata;
}
public double getWyplata(){
return wyplata;
}
public String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata();
}
}
public class Nurse extends Person{
private int nadgodziny;
public Nurse(){}
public Nurse(String imie, String nazwisko, double wyplata, int nadgodziny){
super(imie, nazwisko, wyplata);
this.nadgodziny = nadgodziny;
}
public void setNadgodziny(int nadgodziny){
this.nadgodziny = nadgodziny;
}
public int getNadgodziny(){
return nadgodziny;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getNadgodziny();
}
}
public class Doctor extends Person {
private double premia;
public Doctor(){}
public Doctor(String imie, String nazwisko, double wyplata , double premia){
super(imie, nazwisko, wyplata);
this.premia = premia;
}
public double getPremia(){
return premia;
}
public void setPremia(double premia){
this.premia = premia;
}
#Override
String toString(){
return getImie() + " " + getNazwisko() + " " + getWyplata() + " " + getPremia();
}
}
Can someone help me solve this problem?

The problem lies here, in the Person and Doctor class:
#Override
String toString(){
return ...;
}
you are missing the public specifier. There should be an error / warning about that. Apply it to the method signatures and your code will work as you expect it to.

probably you should add to the List not a Person (object) but a value returned by its toString method:
for(Person person : lista){
stringBuilder.append(person.toString);
stringBuilder.append("\n");
}

Related

Having trouble using the compareTo method

Hey all I've recently been trying to learn the compareTo method but this is extremely confusing.
The goal of this program was to hardcode information into a array of objects and sort it by the test score. The problem is compareTo method which I'm having trouble creating since the book I'm using doesn't go in to detail about this method. Here is the code so far.
public class janesj_Lab7 {
public static void main(String[] args) {
CS_UnderGradStudent no1 = new CS_UnderGradStudent(101,"Nancy","Brown","abc#kean.edu",70.0);
CS_UnderGradStudent no2 = new CS_UnderGradStudent(102,"John", "May","def#kean.edu",90);
CS_GradStudent no3 = new CS_GradStudent(103,"William","Smith","xyz#kean.edu",70,"Database");
Object[] arrays = new Object[3];
arrays[0] = no1;
arrays[1] = no2;
arrays[2] = no3;
int x = (int)Student.getGrade();
Arrays.sort(arrays,0,3);
for(int i = 0;i<arrays.length;i++) {
System.out.println(arrays[i].toString());
}
}
public static abstract class Student implements Comparable<Student>{
public static int studentId;
public static String firstName;
public static String lastName;
public static String email;
public static double testScore;
public static String STUDENT_TYPE;
public static double getGrade(){
return testScore;
}
public static String getStudent() {
return STUDENT_TYPE;
}
public Student(int id,String fname, String lname, String email, double testScore){
this.studentId = id;
this.firstName = fname;
this.lastName = lname;
this.email =email;
this.testScore = testScore;
}
#Override
public String toString() {
String x = Double.toString(testScore);
return "\tStudent ID: " + studentId + " name: "+ firstName + ","+ lastName + " Email: " + email + " testScore: " + x;
}
public abstract String computeGrade();
}
public static class CS_UnderGradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE ="CS_UnderGradStudent";
public CS_UnderGradStudent(int id,String fname, String lname, String email, double testScore) {
super(id,fname,lname,email,testScore);
}
public String computeGrade() {
if( testScore>=70) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString(){
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n\t" + "Grade: " + computeGrade();
}
}
public static class CS_GradStudent extends Student implements Comparable<Student>{
String STUDENT_TYPE = "CS_GradStudent";
String researchTopic;
public CS_GradStudent(int id,String fname, String lname, String email, double testScore,String r) {
super(id,fname,lname,email,testScore);
researchTopic = r;
}
public String computeGrade() {
if(testScore>= 80) {
return "Pass";
}
else {
return "Fail";
}
}
public String toString() {
String x = Double.toString(testScore);
return"student type: " + STUDENT_TYPE + "\n" + super.toString() + "\n" + "Grade: " + computeGrade() + "\nResearch Topic: " + researchTopic;
}
}
}
```

Converting Paypal Checkout Transaction to a Java Object?

I've been working on a Paypal JSON to Java object converter, using Gson. But, it doesn't generate a full Java object. Seems like this conversion would have already been done, but I couldn't find anything.
My technique is to take the Paypal JSON, do replacements of their non-Java element names, then parse that into a Java object that I've defined.
Here's what the Gson looks like:
Gson gson = new GsonBuilder().serializeNulls().create();
JSONObjFromPaypalTrx jsonPaypalTrx = gson.fromJson(paypalTrx, JSONObjFromPaypalTrx.class);
logger.debug("jsonPaypalTrx: " +jsonPaypalTrx);
paypalTrx is the Paypal JSON after the element names are replaced:
paypalTrx: {"id":"PAYID-LXJIHMI92J52777N04488909","intent":"Sale","state":"approved","cart":"25M35194DL227451S","createTime":"2019-11-18T11:42:41Z","Payer":{"paymentMethod":"paypal","status":"VERIFIED","PayerInfo":{"email":"sb-cject591397#personal.example.com","firstName":"John","middleName":"John","lastName":"Doe","payerId":"5V25373K45VBE","countryCode":"US","ShippingAddress":{"recipientName":"John Doe","line1":"1 Main St","city":"San Jose","state":"CA","postalCode":"95131","countryCode":"US"}}},"Transactions":[{"Amount":{"total":"199.99","currency":"USD","Details":{"subtotal":"199.99","shipping":"0.00","handlingFee":"0.00","insurance":"0.00","shippingDiscount":"0.00"}},"ItemList":{},"RelatedResources":[{"Sale":{"id":"80E26736585579458","state":"completed","paymentMode":"INSTANT_TRANSFER","protectionEligibility":"ELIGIBLE","parentPayment":"PAYID-LXJIHMI92J52777N04488909","createTime":"2019-11-18T11:43:00Z","updateTime":"2019-11-18T11:43:00Z","Amount":{"total":"199.99","currency":"USD","Details":{"subtotal":"199.99","shipping":"0.00","handlingFee":"0.00","insurance":"0.00","shippingDiscount":"0.00"}}}}]}]}
Here's the Java object I've defined:
package com.example;
import java.util.List;
/**
* This JSON Object was derived from a Paypal transaction string.
*/
public class JSONObjFromPaypalTrx{
private String id;
private String intent;
private String state;
private String cart;
private String createTime;
private Payer payer;
private List<Transactions> transactions;
public JSONObjFromPaypalTrx() {
}
public String getId(){
return id;
}
public void setId(String input){
this.id = input;
}
public String getIntent(){
return intent;
}
public void setIntent(String input){
this.intent = input;
}
public String getState(){
return state;
}
public void setState(String input){
this.state = input;
}
public String getCart(){
return cart;
}
public void setCart(String input){
this.cart = input;
}
public String getCreateTime(){
return createTime;
}
public void setCreateTime(String input){
this.createTime = input;
}
public Payer getPayer(){
return payer;
}
public void setPayer(Payer input){
this.payer = input;
}
public List<Transactions> getTransactions(){
return transactions;
}
public void setTransactions(List<Transactions> input){
this.transactions = input;
}
public static class ShippingAddress{
private String recipientName;
private String line1;
private String city;
private String state;
private String postalCode;
private String countryCode;
public ShippingAddress() {
}
public String getRecipientName(){
return recipientName;
}
public void setRecipientName(String input){
this.recipientName = input;
}
public String getLine1(){
return line1;
}
public void setLine1(String input){
this.line1 = input;
}
public String getCity(){
return city;
}
public void setCity(String input){
this.city = input;
}
public String getState(){
return state;
}
public void setState(String input){
this.state = input;
}
public String getPostalCode(){
return postalCode;
}
public void setPostalCode(String input){
this.postalCode = input;
}
public String getCountryCode(){
return countryCode;
}
public void setCountryCode(String input){
this.countryCode = input;
}
#Override
public String toString() {
return "ShippingAddress [recipientName: " + recipientName + ", line1: " + line1 + ", city: " + city
+ ", state: " + state + ", postalCode: " + postalCode + ", countryCode: " + countryCode + "]";
}
}
public static class PayerInfo{
private String email;
private String firstName;
private String middleName;
private String lastName;
private String payerId;
private String countryCode;
private ShippingAddress shippingAddress;
public PayerInfo() {
}
public String getEmail(){
return email;
}
public void setEmail(String input){
this.email = input;
}
public String getFirstName(){
return firstName;
}
public void setFirstName(String input){
this.firstName = input;
}
public String getMiddleName(){
return middleName;
}
public void setMiddleName(String input){
this.middleName = input;
}
public String getLastName(){
return lastName;
}
public void setLastName(String input){
this.lastName = input;
}
public String getPayerId(){
return payerId;
}
public void setPayerId(String input){
this.payerId = input;
}
public String getCountryCode(){
return countryCode;
}
public void setCountryCode(String input){
this.countryCode = input;
}
public ShippingAddress getShippingAddress(){
return shippingAddress;
}
public void setShippingAddress(ShippingAddress input){
this.shippingAddress = input;
}
#Override
public String toString() {
return "PayerInfo [email: " + email + ", firstName: " + firstName + ", middleName: " + middleName
+ ", lastName: " + lastName + ", payerId: " + payerId + ", countryCode: " + countryCode
+ ", shippingAddress: " + shippingAddress + "]";
}
}
public static class Payer{
private String paymentMethod;
private String status;
private PayerInfo payerInfo;
public Payer() {
}
public String getPaymentMethod(){
return paymentMethod;
}
public void setPaymentMethod(String input){
this.paymentMethod = input;
}
public String getStatus(){
return status;
}
public void setStatus(String input){
this.status = input;
}
public PayerInfo getPayerInfo(){
return payerInfo;
}
public void setPayerInfo(PayerInfo input){
this.payerInfo = input;
}
#Override
public String toString() {
return "Payer [paymentMethod: " + paymentMethod + ", status: " + status + ", payerInfo: " + payerInfo + "]";
}
}
public static class Amount{
private String total;
private String currency;
private Details details;
public Amount() {
}
public String getTotal(){
return total;
}
public void setTotal(String input){
this.total = input;
}
public String getCurrency(){
return currency;
}
public void setCurrency(String input){
this.currency = input;
}
public Details getDetails(){
return details;
}
public void setDetails(Details input){
this.details = input;
}
#Override
public String toString() {
return "Amount [total: " + total + ", currency: " + currency + ", details: " + details + "]";
}
}
public static class ItemList{
public ItemList() {
}
}
public static class Details{
private String subtotal;
private String shipping;
private String handlingFee;
private String insurance;
private String shippingDiscount;
public Details() {
}
public String getSubtotal(){
return subtotal;
}
public void setSubtotal(String input){
this.subtotal = input;
}
public String getShipping(){
return shipping;
}
public void setShipping(String input){
this.shipping = input;
}
public String getHandlingFee(){
return handlingFee;
}
public void setHandlingFee(String input){
this.handlingFee = input;
}
public String getInsurance(){
return insurance;
}
public void setInsurance(String input){
this.insurance = input;
}
public String getShippingDiscount(){
return shippingDiscount;
}
public void setShippingDiscount(String input){
this.shippingDiscount = input;
}
#Override
public String toString() {
return "Details [subtotal: " + subtotal + ", shipping: " + shipping + ", handlingFee: " + handlingFee
+ ", insurance: " + insurance + ", shippingDiscount: " + shippingDiscount + "]";
}
}
public static class Sale{
private String id;
private String state;
private String paymentMode;
private String protectionEligibility;
private String parentPayment;
private String createTime;
private String updateTime;
private Amount amount;
public Sale() {
}
public String getId(){
return id;
}
public void setId(String input){
this.id = input;
}
public String getState(){
return state;
}
public void setState(String input){
this.state = input;
}
public String getPaymentMode(){
return paymentMode;
}
public void setPaymentMode(String input){
this.paymentMode = input;
}
public String getProtectionEligibility(){
return protectionEligibility;
}
public void setProtectionEligibility(String input){
this.protectionEligibility = input;
}
public String getParentPayment(){
return parentPayment;
}
public void setParentPayment(String input){
this.parentPayment = input;
}
public String getCreateTime(){
return createTime;
}
public void setCreateTime(String input){
this.createTime = input;
}
public String getUpdateTime(){
return updateTime;
}
public void setUpdateTime(String input){
this.updateTime = input;
}
public Amount getAmount(){
return amount;
}
public void setAmount(Amount input){
this.amount = input;
}
#Override
public String toString() {
return "Sale [id: " + id + ", state: " + state + ", paymentMode: " + paymentMode + ", protectionEligibility: "
+ protectionEligibility + ", parentPayment: " + parentPayment + ", createTime: " + createTime
+ ", updateTime: " + updateTime + ", amount: " + amount + "]";
}
}
public static class RelatedResources{
private Sale sale;
public RelatedResources() {
}
public Sale getSale(){
return sale;
}
public void setSale(Sale input){
this.sale = input;
}
#Override
public String toString() {
return "RelatedResources [sale: " + sale + "]";
}
}
public static class Transactions{
private Amount amount;
private ItemList itemList;
private List<RelatedResources> relatedResources;
public Transactions() {
}
public Amount getAmount(){
return amount;
}
public void setAmount(Amount input){
this.amount = input;
}
public ItemList getItemList(){
return itemList;
}
public void setItemList(ItemList input){
this.itemList = input;
}
public List<RelatedResources> getRelatedResources(){
return relatedResources;
}
public void setRelatedResources(List<RelatedResources> input){
this.relatedResources = input;
}
#Override
public String toString() {
return "Transactions [amount: " + amount + ", itemList: " + itemList + ", relatedResources: "
+ relatedResources + "]";
}
}
#Override
public String toString() {
return "JSONObjFromPaypalTrx [id: " + id + ", intent: " + intent + ", state: " + state + ", cart: " + cart
+ ", createTime: " + createTime + ", payer: " + payer + ", transactions: " + transactions + "]";
}
}
Here's a log of jsonPaypalTrx:
jsonPaypalTrx: JSONObjFromPaypalTrx [id: PAYID-LXJIHMI92J52777N04488909, intent: Sale, state: approved, cart: 25M35194DL227451S, createTime: 2019-11-18T11:42:41Z, payer: null, transactions: null]
Is the incomplete jsonPaypalTrx due to my use of inner classes inside JSONObjFromPaypalTrx? Splitting each inner class into separate Java files would be awkward for me to do.
Thanks for helping.
Bob
Given JSON payload uses mixed naming convention: camel case and UPPER_CAMEL_CASE for JSON Objects. So, you need to implement your own FieldNamingStrategy:
class PayPalFieldNamingStrategy implements FieldNamingStrategy {
#Override
public String translateName(Field f) {
return f.getType() == String.class ? f.getName() : FieldNamingPolicy.UPPER_CAMEL_CASE.translateName(f);
}
}
And register it like below:
Gson gson = new GsonBuilder()
.setFieldNamingStrategy(new PayPalFieldNamingStrategy())
.create();
Or, for each object declare name like below:
#SerializedName("Payer")
private Payer payer;
Make your member classes static so that they don't need an outer class reference when they're constructed.
Like: public static class ShippingAddress.
Gson likely doesn't know how to constructor inner classes, but it will know how to construct static member classes.

Print all elements of Array list [duplicate]

This question already has answers here:
How do I print my Java object without getting "SomeType#2f92e0f4"?
(13 answers)
Closed 4 years ago.
i want to print all elements of my array list. Eclipse does not show an error, but it doesnt show the elements that i added in console. Can you please tell me what i did wrong?
The console shows:
Typ:Droide
ID:8282
NameR2D2
HumanoiderRoboter#15db9742
HumanoiderRoboter#6d06d69c
HumanoiderRoboter#7852e922
HumanoiderRoboter#4e25154f
Roboter Class:
public class Roboter {
protected String Name;
protected int ID;
protected String typ;
public Roboter(String Name, int ID, String typ) {
super();
this.Name = Name;
this.ID = ID;
this.typ = typ;
}
public void ausgebenNeu() {
System.out.println("ID:"+ID);
System.out.println("Name:"+Name);
System.out.println("Typ:"+typ);
}
HumanoiderRoboter Class:
import java.util.ArrayList;
public class HumanoiderRoboter extends Roboter {
String RoboterTyp;
public HumanoiderRoboter (String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<HumanoiderRoboter> Sensoren = new ArrayList<HumanoiderRoboter>();
Sensoren.add(new HumanoiderRoboter("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new HumanoiderRoboter("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new HumanoiderRoboter("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
HumanoiderRoboter R2 = new HumanoiderRoboter("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
Currently your problem is the HumanoiderRoboter doesn't overwrite the toString method which results the HumanoiderRoboter#4e25154f stuff. So if you overwrite the toString method it will print your object stuff you put in there:
...
#Override
public String toString() {
return "Typ: " + type + ", ID: " + id + ", Name: " + name;
}
...
Default toString method from Object looks like that:
public String toString() {
return getClass().getName() + "#" + Integer.toHexString(hashCode());
}
So now if you do System.out.println(theObject) it will for example result something like this:
Typ: some, ID: 5, Name: NiceRoboter
And if you want the complete array as one String you can use the Arrays#toString method:
System.out.println(Arrays.toString(yourList.toArray()));
In your Roboter class override toString() method like this:
public class Roboter {
//-----member fields,methods
//Add this method
#Override
public String toString(){
return "{name:"+this.Name+"}";
}
}
Also read this link for naming convention to follow in Java https://www.geeksforgeeks.org/java-naming-conventions/
Override toString() method in Roboter class.
public class Test extends Roboter {
String RoboterTyp;
public Test(String Name, int ID, String typ) {
super(Name, ID, typ);
}
public void ausgeben() {
ArrayList<Test> Sensoren = new ArrayList<Test>();
Sensoren.add(new Test("Sensor1", 4232, "Infrarotsensor"));
Sensoren.add(new Test("Sensor2", 9232, "Lichtsensor"));
Sensoren.add(new Test("Sensor3", 5777, "Touchssensor"));
Sensoren.add(new Test("Sensor4", 3321, "Gyrosensor"));
System.out.println("Typ:" + typ);
System.out.println("ID:" + ID);
System.out.println("Name" + Name);
for (Roboter ele : Sensoren) {
System.out.println(ele);
}
}
public static void main(String[] args) {
Test R2 = new Test("R2D2", 8282, "Droide");
R2.ausgeben();
}
}
public class Roboter {
String Name;
int ID;
String typ;
public Roboter(String name, int iD, String typ) {
super();
Name = name;
ID = iD;
this.typ = typ;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public int getID() {
return ID;
}
public void setID(int iD) {
ID = iD;
}
public String getTyp() {
return typ;
}
public void setTyp(String typ) {
this.typ = typ;
}
#Override
public String toString() {
return "Roboter [Name=" + Name + ", ID=" + ID + ", typ=" + typ + "]";
}
}

Java not showing the output im looking for (Beginner)

Hi guys i am fairly new to Java but ive come across a problem that i cant seem to fix, the problem is in the 'WashingMachine' Class its not displaying the 'spinSpeed' details , any answers will be appreciated
here are my codes:
enter code here
package test;
public class Client {
private String Name;
private String PhoneNo;
Client () {
Name = null;
PhoneNo= null;
}
Client (String N, String P){
Name = N;
PhoneNo = P;
}
public void setName(String N){
Name = N;
}
public void setPhoneNo(String P) {
PhoneNo = P;
}
public String getName(){
return Name;
}
public String setPhoneNo() {
return PhoneNo;
}
public String toString() {
return "\nName: "+ Name + "\nPhoneNo:"+ PhoneNo.toString();
}
}
enter code here
package test;
public class Machine {
private String Make;
private double Price;
private Client Cust;
public Machine(String make, double price, Client cust)
{
Make = make;
Price = price;
Cust = cust;
}
#Override
public String toString() {
return "\n" +"Make of machine: " + Make + "\n" + "Price: " + Price + "\n" + Cust.toString();
}
public String getMake() {
return Make;
}
public double getprice() {
return Price;
}
public Client getcust() {
return Cust;
}
}
enter code here
package test;
public class WashingMachine extends Machine {
private int spinSpeed;
public WashingMachine (String make, double price, Client cust, int spinSpeed){
super(make, price, cust);
}
#Override
public String toString() {
return "WashingMachine [spinSpeed=" + spinSpeed + ", spinSpeed()=" + spinSpeed() + "]";
}
public int spinSpeed() {
return spinSpeed;
}
enter code here
package test;
import java.util.ArrayList;
public class MachinePurchaseTestVerC {
public static void main(String [] args) {
ArrayList<Machine> gadgets = new ArrayList<Machine> ();
Client mCust2 = new Client("Paul", "0487654321");
Client mCust3 = new Client("Chandra", "0487651234");
Client wCust1 = new Client("Catherine", "0412345678");
Client wCust4 = new Client("Mike", "0412348756");
gadgets.add(new WashingMachine("Bosch", 549.50, wCust1, 3500));
gadgets.add(new Machine("Samsung", 678.50, mCust2));
gadgets.add(new Machine("Electrolux", 449.25, mCust3));
gadgets.add(new WashingMachine("LG", 500.00, wCust4, 3200));
for(int i = 0; i<gadgets.size(); i++){
System.out.println(gadgets.get(i).toString());
System.out.println("----------------------------------");
}
}
}
In your WashingMachine class, you forgot to set the speed in your constructor
public WashingMachine (String make, double price, Client cust, int spinSpeed){
super(make, price, cust);
this.spinSpeed = spinSpeed;
}
hope that helps :)

array in a separate class other than main method/class

I keep getting this error, its about needing braces after the array decleration.
I do not know what to do about this. I want to make an array that is not in my main method. I want the array to be supertype populated with subclass.
Here is my code
public class ArrayTest {
Employee [] employees = new Manager[2];
employees[0]= new Manager("Thomas", "Cummings");
}
public class Manager extends Employee{
private int employees;
public Manager() {
super();
employees = 0;
}
public Manager(int employees) {
super();
this.employees = employees;
}
public Manager(String f_name, String l_name) {
super(f_name, l_name);
}
public Manager(String f_name, String l_name, int employees) {
super(f_name, l_name);
this.employees = employees;
}
public int getEmployees() {
return employees;
}
public void setEmployees(int employees) {
this.employees = employees;
}
public void setManager(String f_name, String l_name){
this.setF_name(f_name);
this.setL_name(l_name);
}
public void setManager(String f_name, String l_name, int employees){
this.setF_name(f_name);
this.setL_name(l_name);
this.employees = employees;
}
#Override
public String toString(){
return "\nName " + getF_name() + " " + getL_name() +
"\nEmployee ID " + getEmp_id() +
"\nNum of employees " + getEmployees();
}
}
public class Employee {
private String f_name, l_name;
private static long emp_id = 001;
public Employee(){
f_name = "";
l_name = "";
emp_id ++;
}
public Employee(String f_name, String l_name) {
this.f_name = f_name;
this.l_name = l_name;
emp_id ++;
}
public String getF_name() {
return f_name;
}
public void setF_name(String f_name) {
this.f_name = f_name;
}
public String getL_name() {
return l_name;
}
public void setL_name(String l_name) {
this.l_name = l_name;
}
public long getEmp_id() {
return emp_id;
}
public void setEmp_id(long emp_id) {
Employee.emp_id = emp_id;
}
public String toString(){
return "\nName " + getF_name() + " " + getL_name() +
"\nEmployee ID " + getEmp_id();
}
}
The reason of error is the following statement:
employees[0]= new Manager("Thomas", "Cummings");
as you cannot put executable statements outside of code blocks(methods, blocks, constructors) in a java class.
One way to resolve this problem is by moving the initialization statement in a constructor:
public class ArrayTest {
Employee [] employees = new Manager[2];
public ArrayTest() {
employees[0]= new Manager("Thomas", "Cummings");
}
}
employees[0]= new Manager("Thomas", "Cummings");
this is an statement which needs to be placed in proper executable block (method, constructor, initialization block)

Categories