简体   繁体   中英

Trying to print a subclass method in a main class in java

I have three classes. An abstract class, a derived class and a main class. I am trying to print the method in the derived class in the main class.

public abstract class newsPaperSub {
    public String name;
    public abstract void address();
    public double rate;
}

Derived class:

import java.util.Scanner;
public class PhysicalNewspaperSubscription extends newsPaperSub {
    @Override
    public void address () {
        String subAddress = " ";
        Scanner input = new Scanner(System.in);
        int i;
        int digitCount = 0;
        for (i = 0; i < subAddress.length(); i++) {
            char c = subAddress.charAt(i);
            if (Character.isDigit(c)) {
                digitCount++;
                System.out.println("Pease enter an address: ");
                 subAddress = input.nextLine();
                if (digitCount <= 1) {
                    rate = 15;
                    System.out.println("Your subscrption price is: " + rate);
                }
            }
        }
    }
}

Main class: I havent been able to figure out what to exactly put in the main class in order to print the function in the derived class. I have tried a couple things with no luck. Any help would be greatly appreciated.

public class demo {
    public static void main (String [] args) {

    }
}

Just put inside of the main method

PhysicalNewspaperSubscription subscription= new PhysicalNewspaperSubscription()

and then call your method

subscription.address()

in the main method as well.

Simply put:

public class demo {
  public static void main (String [] args) {
    PhysicalNewspaperSubscription pns = new PhysicalNewspaperSubscription();
    pns.address();
  }
}

... but your code will not do anything.

The reason being because though you have a Scanner to read in something from the console, it'll never run that piece of code because the following loop structure never runs:

for (i = 0; i < subAddress.length(); i++) {
   ...
}

The reason it does not run is because when you declare subAddress you set it to an empty String ( String subAddress = " "; ), so when the loop checks the condition ( i < subAddress.length() ) it'll evaluate FALSE , because 0 < 0 is FALSE and hence not run the loop.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM