#java #reference #subclass #super
#java #ссылка #подкласс #супер
Вопрос:
Это код, на который вы можете ссылаться, когда вам интересно, чего я пытаюсь достичь:
import java.util.EmptyStackException;
public class TicketMain {
public static void main(String[] args) {
// Create a Student Ticket
StudentTicket t1 = new StudentTicket(100,true);
t1.setPromotionCode("KEXP call-in winner");
System.out.println(t1);
// Generate a general ticket
Ticket t2 = new Ticket(55, 40);
System.out.println(t2);
// Generate a student ticket
StudentTicket t3 = new StudentTicket(90,false);
t3.setPromotionCode("KEXP call-in winner");
System.out.println(t3);
// Check for equality
System.out.println("Ticket t1 and Ticket t2 are equal: " t1.equals(t2)); // Should return false
System.out.println("Ticket t1 and Ticket t3 are equal: " t1.equals(t3)); // Should return true
// Total tickets generated
System.out.println("Total Tickets generated so far: " Ticket.getTicketCount());
}
}
class Ticket {
private double price;
private int daysEarly;
private String promotionCode;
private static final String emptyString = "";
private static int ticketID; // Generates ticket number
public Ticket (double price, int daysEarly) { // Constructs ticket with given price, # of days early, no promo, assigns ticket #
this.price = price;
this.daysEarly = daysEarly;
ticketID = 1;
if (ticketID < 0) {
throw new EmptyStackException();
}
}
public int getDaysEarly(){
return daysEarly;
}
public double getPrice() {
return price;
}
public String getPromotionCode(){
if (promotionCode == null) return emptyString;
if (promotionCode.equals("KEXP call-in winner")) promotionCode = ("KEXP call in winner (student)");
return promotionCode;
}
public String setPromotionCode(String code){
if (code == null) throw new Error();
this.promotionCode = code;
return promotionCode;
}
public String toString(){
return "Ticket ID: " ticketID ", Price: $" getPrice() ", Days Early: " getDaysEarly() ", Promotion Code: " getPromotionCode() ".";
}
public static int getTicketCount(){
return ticketID;
}
public boolean equals(Ticket one) {
if (price == one.price amp;amp; promotionCode.equals(one.promotionCode)) return true;
else return false;
}
}
Ниже приведена область, в которой я пытаюсь выполнить математику для суперпараметров…
Я помещаю «price / 2» в параметр sub, чтобы позаботиться о математике, но мне все еще нужен другой «оператор if» метафорически
class StudentTicket extends Ticket {
private static final int daysEarly = 14;
public StudentTicket(double price, boolean honors) {
/*
Student tickets are always bought by campus ticket sales agency, two weeks in advance.
Students always get 50% off initial price.
Honor students get an addition $5 off after the 50%, down to a minimum of $0.
Student tickets have special promo codes.
*/
super(price/2, daysEarly);
// HOW DO I CALL UPON SUPER AFTER ALREADY HAVING DONE SO ???
// I STILL NEED TO SUBTRACT 5 BASED ON HONORS BOOLEAN OF SUBCLASS
// HOW DO I ADD AN IF STATEMENT INTO PARAM OF SUPER ???
// All you will do is make a call to super constructor and pass appropriate parameters
// So the idea is when I create a instance of StudentTicket and return price it should return me a discounted.
// That means you need to override the getPrice() method in superclass to update the ticket price
}
}
Мне сказали переопределить метод getPrice, но я не знаю ни одного способа доступа к подпараметрам
Комментарии:
1. Я думаю, что самый простой способ — объявить
price
поле какprotected
, чтобы вы могли получить к нему доступ из подкласса.
Ответ №1:
Вы могли бы создать метод setPrice() в классе ticket:
...
public int getDaysEarly(){
return daysEarly;
}
public void setPrice(double newPrice){
price = newPrice;
}
public double getPrice() {
return price;
}
...
Затем сделайте это в конструкторе StudentTicket:
public StudentTicket(double price, int daysEarly, boolean honors) {
super(price/2, daysEarly);
if(honors == true)
setPrice(getPrice() - 5);
}
Поскольку ваши методы имеют тип: public, а StudentTicket является дочерним классом Ticket, он должен иметь возможность доступа и использования любых общедоступных или защищенных методов от своего родителя.
- Или вы могли бы поступить так, как упоминал хаоюй Ван, и объявить цену как защищенную.