I am having a problem when trying to print my ticket(child class) which is all my superclass variables are null or zero not initialized.
this is my superclass:-
public class movie {
protected int movieID;
protected String movieTitle;
movie(){};
movie(int movieID , String movieTitle ){
this.movieID = movieID;
this.movieTitle = movieTitle;
}
}
this is my childclass
public class ticket extends movie{
private int Number_of_ticket;
private int show_number ;
ticket(int Number_of_ticket , int show_number){
this.Number_of_ticket = Number_of_ticket;
this.show_number = show_number;
}
public void print_the_tacket(){
System.out.println("movie id is " + super.movieID);
System.out.println("movie name is " + super.movieTitle);
System.out.println("number of the ticket is " + Number_of_ticket);
System.out.println("show number is " + show_number);
}
}
the main
public class Main {
public static void main(String[] args) {
movie MyMovie = new movie(1234, "spiderman");
ticket myticket = new ticket(34 , 334);
myticket.print_the_tacket();
}
}
my output is
movie id is 0
movie name is null
number of the ticket is 34
show number is 334
I expect when I print my ticket the movie information why I am getting null values What is wrong here? thank you in advance.
When you reference super in the child class, it not bound to the Movie object you created in the main(). That is why you are getting a null value. Look here when I debug the code.
If you want to access the Movie object you created in main(), you can pass it and that will work.
To explain..
Note 1: There are 2 constructors created here. One is movie() without arguments, the other is with 2 arguments. What you extend and call is #1 not #2
public class movie {
protected int movieID;
protected String movieTitle;
movie() { //#1 - no args, so movieID=null, movieTitle=null
//you can debug by adding this line.
this.movieID = 1;
this.movieTitle = "I should not be printing this";
}
movie(int movieID , String movieTitle ){ //#2 - has args.
this.movieID = movieID;
this.movieTitle = movieTitle;
}
}
Note 2: Your problem is in ticket, when you do not write super(..) with args you are passing nothing, hence it is calling movie() without parameters. So if you are calling movie(), you get non declared variables. If you see sample above for debug you should see 1 and "I should not print this" instead to explain the scenario.
public class ticket extends movie{
private int Number_of_ticket;
private int show_number ;
ticket(int Number_of_ticket , int show_number){
//Not visible, but actually triggers super() and calling movie #1, not super(arg1, args2)
//super(1,"movie")
this.Number_of_ticket = Number_of_ticket;
this.show_number = show_number;
}
}
Note 3: You are making 2 different objects, object #1 is movie, and object #2 is ticket. To me it seems you only want 1 object which is ticket that extends movie. What happens here is that the codes are 2 different/seperated objects and they are not tied together.
public class Main {
public static void main(String[] args) {
movie MyMovie = new movie(1234, "spiderman"); //#Object 1
ticket myticket = new ticket(34 , 334); //#Object 2
myticket.print_the_tacket();
}
}
Approach: You may want the codes to be the following way where you create movie and ticket together in ticket call. This means when you create ticket your movie must be created. In a nutshell no movie created, no tickets to issue.
public class Movie { //Class name should always be captialized
protected int movieID; //you can declare final
protected String movieTitle;
Movie(int movieID , String movieTitle ){ //Only this
this.movieID = movieID;
this.movieTitle = movieTitle;
}
}
public class Ticket extends Movie { //Captialize class
private int Number_of_ticket; //should avoid _ and use Snakecase
private int show_number ;
Ticket(int Number_of_ticket , int show_number, int movieID, String movieTitle){
super(movieId, movieTitle); //always and must create movie object
this.Number_of_ticket = Number_of_ticket;
this.show_number = show_number;
}
public void print_the_tacket(){ //should use snake case printTheTacket
System.out.println("movie id is " + super.movieID);
System.out.println("movie name is " + super.movieTitle);
System.out.println("number of the ticket is " + Number_of_ticket);
System.out.println("show number is " + show_number);
}
}
public class Main {
public static void main(String[] args) {
Ticket myticket = new Ticket(34 , 334, 1234, "spiderman");
myticket.print_the_tacket();
}
}
Much ideal is that movie is created in ticket instead of passing 2 arguments or extending. In this case both are separated and tied and incase in future movie has also things like PG-13, GA parameters you can expand it. But i guess it's for school understanding on inheritance, your example fits for now.
public class Ticket {
private int numberOfTickets;
private int showNumber ;
private Movie movie;
Ticket(int numberOfTickets , int showNumber, Movie movie){
this.numberOfTickets = numberOfTickets;
this.showNumber = showNumber;
this.movie = movie
}
public void printTheTacket(){
System.out.println("movie id is " + movie.movieID);
System.out.println("movie name is " + movie.movieTitle);
System.out.println("number of the ticket is " + numberOfTickets);
System.out.println("show number is " + showNumber);
}
}
Related
I´m new to programming and I have this task to implement a simple booking System for bus tickets.
We´re supposed to implement a method that adds new bus routes using the attributes: busNumber, start, destination, price, currency. To save the bus routes I´m using an arraylist and save new objects like this:
Booking.add(new Booking(1, "France", "Latvia", 2.05, Currency.EUR))
My issue now is working with those objects since they don´t have a name. I don't know the exact number of objects, so I have to do it this way (i think so at least). Where the issue occurred is at the method "remove", that is supposed to remove a bus route. I thought I could use an Iterator to iterate through the ArrayList and compare the busNumbers but it´s not working.
Another issue I have is, that when I want to print all the objects in my Array list it just prints the last object as many times as there are objects in my ArrayList. Also, my method and attributes are all static now otherwise I wouldn´t know how to use them in another class.
Does anybody has some advice for a newbie please?
My Code is below:
import java.util.ArrayList;
import java.util.Iterator;
public class Booking {
static int busNumber;
static int customerID = 1; //First customerID starts with 1
static String name;
static double price;
static int invoiceNumber = 1; //First invoicenumber starts with 1.
static String start;
static String destination;
static Currency currency;
static ArrayList<Booking> bookable = new ArrayList<Booking>();
//Constructor
public Booking(int busNumber, String start, String destination, double price, Currency currency) {
this.busNumber = busNumber;
this.start = start;
this.destination = destination;
this.price = price;
this.currency = currency;
}
public int getBusNumber() {
return busNumber;
}
public static void add(Booking add) { // add-method. Adds the bus routes to the booking system
bookable.add(add);
}
public static void remove(int busNumber) { // Here´s one of my issues. That´s what i have.
Iterator<Booking> it = bookable.iterator();
if ( == busNumber) {
bookable.remove(it);
}
}
public static void listRoute() {
for (Booking element : bookable) {
Terminal.printLine(toString(element));
}
}
public static String toString(Booking element) {
return "000" + busNumber + " " + start + " " + destination + " " + price + " " + currency;
}
}
My second class which is later supposed to be the UI:
public class Input {
public static void main(String[] args) {
Booking.add(new Booking(1, "Mannheim", "Karlsruhe", 2.05, Currency.EUR));
Booking.add(new Booking(2, "Heidelberg", "Karlsruhe", 3.05, Currency.JPY));
Booking.add(new Booking(3, "Germersheim", "Karlsruhe", 4.05, Currency.USD));
Booking.listRoute();
}
}
The Output is: "0003, "Germersheim", "Karlsruhe", 4.05, Currency.USD" 3 times..
I have created a class called Album, which is this one:
public class Album {
private String Titulo;
private int temas;
private int ano;
public Album(String Titulo2, int temas2, int ano2) {
this.Titulo = Titulo2;
this.temas = temas2;
this.ano = ano2;
}
public Album(String Titulo2, int temas2) {
this.Titulo = Titulo2;
this.temas = temas2;
}
public int getAno() {
return this.ano;
}
public int getTemas() {
return this.temas;
}
public String getTitulo() {
return this.Titulo;
}
public void setAno(int ano) {
this.ano = ano;
}
public boolean foiEditadoNesteSeculo() {
if (this.ano > 2000) {
return true;
} else {
return false;
}
}
public void adicionaTemasBonus(int x) {
this.temas += x;
}
public void mostraAlbum() {
System.out.println(this.Titulo + " (editado em " + this.ano + "; tem " + this.temas + " temas)");
}
}
It works fine. The problem is that the teacher asked me to create a new class called Band and it has to have an array of Albums. The Band object should be declared with an int that represents the limit of the number of albums (the length of the array). I already have some idea on how to work with arrays, but I have no idea on how to create a type of array that contains objects from another class, and after how to use the attributes of the objects to return something. I think I can figure out the rest after I'm able to properly create the class, though.
Apologies, as it has been described in Portuguese and I don't have much experience in translating.
In my opinion this would be easier to manage with a List so you can add as many Albums as you want at any time, however, since the problem statement required Array I made an example of a Band class.
I also included main method to test the program at the bottom of the Band class:
public class Band {
private int totalAlbums;
private Album[] albums;
private int currentNumberOfAlbums;
public Band(int totalAlbums) {
this.totalAlbums = totalAlbums;
this.albums = new Album[totalAlbums];
this.currentNumberOfAlbums = 0;
}
public Band(Album[] albums) {
this.totalAlbums = albums.length;
this.albums = albums;
this.currentNumberOfAlbums = this.totalAlbums;
}
public void addNewAlbum(String titulo, int temas, int ano) {
if (this.currentNumberOfAlbums == totalAlbums) {
System.out.println("Warning: Cannot add any more albums, limit reached.");
return;
}
this.albums[this.currentNumberOfAlbums++] = new Album(titulo, temas, ano);
}
public void printAlbums() {
for (Album a : this.albums) {
a.mostraAlbum();
}
}
public static void main(String [] args) {
Band b = new Band(3);
b.addNewAlbum("The First", 4, 2001);
b.addNewAlbum("The Second", 98, 2055);
b.addNewAlbum("The Finale", 12, 2011);
b.addNewAlbum("The Extra", 12, 2111);
b.printAlbums();
}
}
There are a few things to look for in this code.
First, to address your direct question, you can simply use a custom class as an array like any other class/primitive with Album[].
Secondly, you will require a Band constructor that instantiates the array of Album based on an integer passed to it, so you know how many albums are the limit. You can see this with the this.albums = new Album[totalAlbums]; line.
Next, you need a way to add a new Album into the array of Album[]. This can be done a few different ways, but the way I chose was to create a method addNewAlbum(String, int, int) to do it for this example which will also increase currentNumberOfAlbums by 1 every time a new album is added. This is useful so you know when an Album is attempted to be added even though the totalAlbums are already full! This will prevent an ArrayIndexOutOfBoundsException in your code if addNewAlbum is called too many time.
Lastly, in addNewAlbum you need to call your Album constructor with new Album(titulo, temas, ano).
In my example main, a Band with limit of 3 albums is created, and 4 albums are attempted to be added into it, with the first 3 adding successfully, and the 4th not being added, but instead printing a warning for being outside the limit.
I also added a printAlbums() method which will use your mostraAlbum() to print each Album in the albums array.
Output:
Warning: Cannot add any more albums, limit reached.
The First (editado em 2001; tem 4 temas)
The Second (editado em 2055; tem 98 temas)
The Finale (editado em 2011; tem 12 temas)
EDIT:
I added the Band(Album[] albums) constructor, you can call this with:
Album[] albums = new Album[3];
//Add your albums into this variable
Band b = new Band(albums);
public class Band {
private Album[] albums;
private numberOfAlbums;
//...
// create an empty constructor
Band(){
albums = new Album[];
numberOfAlbums = 0;
}
// constructor that receives the albums
Band(Album[] albums){
this.albums = albums;
this.numberOfAlbums = albums.length;
}
// constructor that receives the number of albums
Band(int numOfAlbums){
this.numberOfAlbums = numOfAlbums;
this.albums = new Album[numOfAlbums];
}
// add getters and setters
// example of adding a new album
public void addNewAlbum(Album album){
if(this.numOfAlbums == this.albums.length){
// you need to create a new array with a bigger size, copy the existing data and insert the album
// or whatever you'd like
} else {
this.albums[this.numOfAlbums] = album;
// increment the numOfAlbums
this.numOfAlbums++;
}
}
}
private class Album {
//...
}
You just need to add [] to define that the field is an array.
public class Band {
private int totalAlbums;
private Album[] albums;
//...
}
private class Album {
//...
}
I hope this example helps you.
private Album[] albums; // array of album
private int albumLimit; // limit for album
public Band(int albumLimit) {
this.albumLimit = albumLimit; // initialize limit
this.albums = new Album[albumLimit]; // set limit of album array
}
// here it creates a new Album every time the loop runs
// you can fill the array in other ways too
public void fillAlbum() {
for (int i = 0; i < albumLimit; i++) {
String name = "name_" + i;
int team = i;
albums[i] = new Album(name, team);
}
}
public void printAlbum() {
for (int i = 0; i < albumLimit; i++) {
System.out.println("Name :" + albums[i].getTitulo());
System.out.println("Team :" + albums[i].getTemas());
System.out.println();
}
}
}
This question already has answers here:
Why does my ArrayList contain N copies of the last item added to the list?
(5 answers)
Closed 6 years ago.
This if my first question on stackoverflow. I can usually find answers myself but I'm having trouble with this one. I've got 2 objects, "Book", and "Periodical". These are subclasses to a class "Publication". Now, I'm trying to add 3 instances of "Book" and 3 instances of "Periodical" to an ArrayList. I'm having trouble figuring out how to do this.
With this current code, I get an error "no suitable method found for add(Book,Book,Book,Periodical,Periodical,Periodical).
Here is the current code:
import java.util.ArrayList;
import java.util.Date;
public class DriverProgram {
public static void main(String[] args) {
// Instantiate 3 instances of each object.
Book book1 = new Book(1234, 1, "James", 100, "Hello", "Berkwood Inc.", new java.util.Date(), "History");
Book book2 = new Book(2345, 2, "Ralph", 200, "Goodbye", "Shackles Co.", new java.util.Date(), "English");
Book book3 = new Book(3456, 3, "Julia", 300, "Hello Again", "Trustin Inc.", new java.util.Date(), "History");
Periodical periodical1 = new Periodical("Daily", "Dylan", "History 101", "History Inc.", new java.util.Date(), "History");
Periodical periodical2 = new Periodical("Weekly", "Jannette", "Mathematics 101", "Mathematics Inc.", new java.util.Date(), "Mathematics");
Periodical periodical3 = new Periodical("Monthly", "Patricia", "Science 101", "Science Inc.", new java.util.Date(), "Science");
// Create an array list of the Publication class type, and add the objects to it.
ArrayList <Publication> publications = new ArrayList<Publication>();
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
// Pass the array list to a method to loop through it and display the toString methods.
displayObjects(publications);
} // End of main
static void displayObjects (ArrayList<Publication> publications) {
// Loop through array list and display the objects using the toString methods.
for (Publication p : publications) {
System.out.print(p.toString());
} // End of for each loop
} // End of displayObjects
} // End of DriverProgram class
I've also tried changing:
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
To this:
publications.add(book1);
publications.add(book2);
publications.add(book3);
publications.add(periodical1);
publications.add(periodical2);
publications.add(periodical3);
Which rids my program of the compiler error, but then it just prints the "periodical3" object, 6 times. I'm not sure what I'm doing wrong. Any suggestions? Thank you in advance! :)
EDIT:
Here is my Book class:
public class Book extends Publication{
private static int isbn = 0;
private static int libraryOfCongressNbr = 0;
private static String author = "";
private static int nbrOfPages = 0;
// Constructor for Book class with parameters for each attribute.
public Book(int newISBN, int newLibraryOfCongressNbr, String newAuthor, int newNbrOfPages, String newTitle, String newPublisher, java.util.Date newPublicationDate, String newSubject) {
super(newTitle, newPublisher, newPublicationDate, newSubject);
isbn = newISBN;
libraryOfCongressNbr = newLibraryOfCongressNbr;
author = newAuthor;
nbrOfPages = newNbrOfPages;
}
/////////////////////////////////////////////////////// Getters ///////////////////////////////////////////////////////
int getISBN() {
return isbn;
}
int getLibraryOfCongressNbr() {
return libraryOfCongressNbr;
}
String getAuthor() {
return author;
}
int getNbrOfPages() {
return nbrOfPages;
}
/////////////////////////////////////////////////////// Setters ///////////////////////////////////////////////////////
void setISBN(int newISBN) {
isbn = newISBN;
}
void setLibraryOfCongressNbr(int newLibraryOfCongressNbr) {
libraryOfCongressNbr = newLibraryOfCongressNbr;
}
void setAuthor(String newAuthor) {
author = newAuthor;
}
void setNbrOfPages(int newNbrOfPages) {
nbrOfPages = newNbrOfPages;
}
//toString method for Book class
public String toString () {
StringBuilder result = new StringBuilder();
result.append("\nISBN: " + isbn + "\n");
result.append("\nPublisher: " + libraryOfCongressNbr + "\n");
result.append("\nAuthor: " + author + "\n");
result.append("\nNumber of Pages: " + nbrOfPages + "\n");
result.append("--------------------------------------------------------- ");
return super.toString() + result.toString();
} // End of toString
} // End of Book class
My Periodical class is identical, but here is my Publication class:
import java.util.Date;
public abstract class Publication {
// Data fields.
private static String title = "";
private static String publisher = "";
private static java.util.Date publicationDate;
private static String subject = "";
// Constructor for Publication class with parameters for each attribute.
public Publication(String newTitle, String newPublisher, java.util.Date newPublicationDate, String newSubject){
title = newTitle;
publisher = newPublisher;
publicationDate = newPublicationDate;
subject = newSubject;
}
/////////////////////////////////////////////////////// Getters ///////////////////////////////////////////////////////
String getTitle() {
return title;
}
String getPublisher() {
return publisher;
}
java.util.Date getPublicationDate() {
return publicationDate;
}
String getSubject() {
return subject;
}
/////////////////////////////////////////////////////// Setters ///////////////////////////////////////////////////////
void setTitle(String newTitle) {
title = newTitle;
}
void setPublisher(String newPublisher) {
publisher = newPublisher;
}
void setPublicationDate(java.util.Date newPublicationDate) {
publicationDate = newPublicationDate;
}
void setSubject(String newSubject) {
subject = newSubject;
}
//toString method for Publication class
public String toString () {
StringBuilder result = new StringBuilder();
result.append("\nTitle: " + title + "\n");
result.append("\nPublisher: " + publisher + "\n");
result.append("\nPublication Date: " + publicationDate + "\n");
result.append("\nSubject: " + subject + "\n");
return result.toString();
} // End of toString
} // End of Publication class
Let me know if you need anything else!
EDIT x2: Sorry, I realize my post is getting quite long.
So I've gotten rid of all "static" keywords from my class variables, or "data fields" as I've called them in my code. I then changed my code back to this code:
ArrayList <Publication> publications = new ArrayList<Publication>();
publications.add(book1);
publications.add(book2);
publications.add(book3);
publications.add(periodical1);
publications.add(periodical2);
publications.add(periodical3);
And it works! It executes as it should! I just one question though, since this code doesn't seem to work:
publications.add(book1, book2, book3, periodical1, periodical2, periodical3);
Is there a shorter way to add all of the objects to the ArrayList with out doing it one by one?
If I understand the problem correctly, you have 6 Publication objects, and you are only seeing the values of the most recently created one.
That would likely be caused because you have static class variables instead of instance variables.
For example
class A {
static int x; // class variable
int y; // instance variable
public A(int val) {
x = val; // All 'A' classes now have x = val;
y = val; // Only 'this' class has y = val;
}
}
If I were to run this
A a1 = new A(4);
A a2 = new A(5);
System.out.println(a1.x);
Then I would see it print 5 and not 4, which describes the scenario you are seeing because you have assigned all variables in the Publication class to those that you use during the last call of new Periodical.
The solution is to not use static variables if you want to have multiple instances of a class with their own values.
I am making a program that simulates a Store and a Member. I am trying to write a method, memberRegister2(). This method is the the Store class but calls the constructor from the Member class to make a member object. This method is to be passed the name, id and pinNumber as parameters and then creates the Member object, which is to be stored in a local variable 'member'. I have no idea how to do this. As you will see from the code below I have tried to use the 'Member member = new Member()' But i do not know how to make the parameters user input.
(P.S I am using BlueJ)
Here is my code for both classes hopefully making my question make more sense. I am very new to java so excuse bad coding.
public class Store
{
// instance variables
private String storeName;
private int total;
//Member member;
/**
* Constructor for objects of class Store
*/
public Store(String newStoreName, int newTotal)
{
// initialise instance variables
storeName = newStoreName;
total = newTotal;
}
//Accessor Methods
public String getStoreName()
{
return storeName;
}
public int getTotal()
{
return total;
}
public void memberRegister1(Member newMember)
{
System.out.println("Salford Thrifty " + storeName + ": Welcome " + newMember.getName() + " (id:" + newMember.getId() + ")" );
}
public void memberRegister2()
{
//Member member = new member(memberName, memberId, memberPinNumber);
}
//Mutator Methods
public void newStoreName(String newName)
{
storeName = newName;
}
public void newTotal(int newTotal)
{
total = newTotal;
}
}
and the Member class
public class Member
{
// instance variables
private String name;
private String id;
private String pinNumber;
/**
* Constructor for objects of class Member
*/
public Member(String memberName, String memberId, String memberPinNumber)
{
// initialise instance variables
name = memberName;
id = memberId;
pinNumber = memberPinNumber;
}
public Member()
{
// initialise instance variables
name = "Bob";
id = "ASD123";
pinNumber = "5678";
}
//Accessor Methods
public String getName()
{
return name;
}
public String getId()
{
return id;
}
public String getPinNumber()
{
return pinNumber;
}
//Mutator Methods
public void newName(String newMemberName)
{
name = newMemberName;
}
public void newId(String newMemberId)
{
name = newMemberId;
}
public void newPinNumber(String newMemberPinNumber)
{
name = newMemberPinNumber;
}
}
I have been told to keep the variable at the top private and use pointers? Not sure what this means but it has not been explained to me very well.
You can a Scanner to read the user's input like so.
Scanner s = new Scanner(System.in);
String userInput = s.nextLine();
Then just initialize your member instance using the strings entered by the user.
String memberName, memberId, memberPin;
Scanner s = new Scanner(System.in);
System.out.println("Enter a name");
memberName = s.nextLine();
System.out.println("Enter an id");
memberId = s.nextLine();
System.out.println("Enter a pin");
memberPin = s.nextLine();
Member m = new Member(memberName, memberId, memberPin);
Also, you probably want to make pin, and maybe the id ints instead of strings.
Here's something I have from an old class that should show you how:
SavingsAccount myAccount = new SavingsAccount(200, 5);
So when you want to create an object from another class you have to use that second class to initialize it as shown above the SavingsAccount is like int it instantiates the object and then the two integers SavingsAccount(200, 5); is used because the method within the second class is instantiated with two integers of its own so the object you are creating must have two integers of its own. And what I mean by the method has two integer instantiated is as shown in the code below:
public SavingsAccount(double amount, double rate)
{
super(amount);
interestRate = rate;
}
if you do not instantiate a method with two objects within the parentheses then you do not need them within:
SavingsAccount myAccount = new SavingsAccount(200, 5);
I hope this helps any with your question i'm fairly new myself and am trying to help with as much as I can My course uses BlueJ as well and I know a good bit about BlueJ so I hope this helps.
I'm a beginner in Java programming, I tried everything I could but I cant seems to troubleshoot my problem.
The problem Im facing is the getCardID() methods keep returning null value, the getTokenBalance() seems to work fine, or do i need special code to return a string value from getCardID()?
Any help is very much appreciate.
This is Prepaidcard.java class:
class PrepaidCard {
private String cardID;
private int tokenBalance;
public PrepaidCard(String id) { // My First Constructor
String cardID = id ;
}
public PrepaidCard(String id, int token) { // My Second Constructor
String cardID = id;
tokenBalance = token;
}
public void addToken(int token) { // Methods
tokenBalance =token+tokenBalance;
}
public void deductToken(int token) { // Methods
tokenBalance=tokenBalance-token;
}
public int getTokenBalance() { // Methods
return tokenBalance;
}
public String getCardID() { // Why does this method keep returning null value?
return cardID;
}
}
This is the class use to test prepaidcard.java
import java.util.*;
class testprepaid {
public static void main(String [] args) {
Scanner sc = new Scanner(System.in);
System.out.print("Insert card1 id : ");
String newid = sc.nextLine(); // my scanner class that read user input in String
System.out.print("Insert card2 id : ");
String newid2 = sc.nextLine(); // my scanner class that read user input in String
System.out.print("Enter Card2 initial token : ");
int itoken = sc.nextInt();
PrepaidCard card1 = new PrepaidCard(newid); // object created base on 1st & 2nd Constructor
PrepaidCard card2 = new PrepaidCard(newid2,itoken);
System.out.println("Card1 ID: " + card1.getCardID()); // the method return null when called
System.out.println("Card1 token balance : " + card1.getTokenBalance());
System.out.println("Card2 ID: " + card2.getCardID()); // and this
System.out.println("Card2 token balance : " + card2.getTokenBalance());
And other line contains no error so I didn't add them.
You can see my runtime error here.
In your constructor, you declared a new local variable:
public PrepaidCard(String id, int token) {// My Second Constructor
String cardID = id; //This should be cardID = id;
tokenBalance = token;
}
Depending on your IDE, you may enable warnings that could tell you about uninitialized private members.
String cardID = id ;
should be a instance variable.
So remove local declaration of String cardID -
public PrepaidCard(String id){ //My First Constructor
cardID = id ;
}