How do you shadow a final variable from a parent class? - java

I have a parent class in which i have a final static int which i need to shadow in a child class. In the parent class i use a method "print", which i override in my child class. If i use this code, the method print will use the MINIMUMPRIJS from my parent class. How can i make it use the MINIMUMPRIJS from my childclass?
In my taskdescription it says about the class "reis":
- Make sure the price is at least 5 euros. Create a variable for this and make sure this minimumprice is always guaranteed.
- 1 constructor with 1 paramter (destination)
- 1 constructor with paramters (destiantion, price)
about the class "vliegtuigreis"
- In here the minimumprice is 25 euros. Do what is needed.
- 1 constructor with just 1 paramater (destination)
- 1 constructor with paramaters (destination, price, and flightnumber)
public abstract class Reis {
public final static int MINIMUMPRIJS = 5;
public void setPrijs(double prijs) {
if (prijs >= getMINIMUMPRIJS()) {
this.prijs = prijs;
}else{
this.prijs = MINIMUMPRIJS;
}
}
public void print(){
System.out.printf("Reis met bestemming %s kost %,.2f euro. %n", bestemming, prijs);
}
}
public class VliegtuigReis extends Reis {
private final static int MINIMUMPRIJS = 25;
public void print(){
super.print();
System.out.println("Vluchtnr " + vluchtnummer);
}
}

You can define constants for default values, but then use fields to store dynamic values. You don't need to "shadow" the minimum price of the parent at all, you merely refer to a different constant in the child.
public abstract class Parent {
public static final double MIN_PRICE = 5.0;
private double price;
public Parent() {
this(MIN_PRICE);
}
public Parent(double price) {
this.price = Math.max(price, Parent.MIN_PRICE);
}
public print() {
System.out.println("Price is: " + this.price);
}
}
public class Child extends Parent {
private static final double MIN_PRICE = 25.0;
public Child() {
super(Child.MIN_PRICE);
}
public Child(double price) {
super(Math.max(price, Child.MIN_PRICE));
}
public void print() {
super.print();
System.out.println("Other stuff");
}
}
Hopefully you can take this and expand it to the rest of your requirements.

Related

"Triangle 1 is abstract; Cannot be instantiated" Driver error

Coming across problems with not being able to to be instantiated even extending and trying to override it does nothing to fix it. Trying with a driver file and 2 other files to print results back. Been stuck for awhile, anything is appreciated at this point.
public abstract class Triangle extends Lot
implements Comparable< TestTriangle> {
public abstract double calculateArea();
public abstract String getID();
public int compareTo(LotType1 o) {
if (calculateArea() > o.calculateArea()) {
return 1;
} else if (calculateArea() < o.calculateArea()) {
return -1;
} else {
return 0;
}
}
#Override
public String toString() {
return "Lot ID: " + getID()
+ " Area: " + calculateArea();
}
}
Driver File =====
public class TestLots {
public static void main(String args[]){
Lot[] lots = {new Triangle1("L1",350, 200) {},
new Triangle2("L2",100,270),
new Triangle1("L3",100, 270),
new Triangle2("L4",350,200)
};
java.util.Arrays.sort(lots);
// print out sorted results
for (Lot lot: lots) {
System.out.print(lot + " ");
System.out.println();
}
An abstract class cannot be initiated.
For you needs, first remove the abstract keyword from the class implementation.
Then, Create an constructor which get your 3 parameters, implement the 2 methods, calculateArea and getID.
Please try to start with this following code
import java.util.Comparator;
public class Triangle implements Comparator<Triangle> {
private String id;
public Triangle(String id) {
this.id = id;
}
public double calculateArea() {
int area = 0;
//calculate your area
return area;
}
public String getID() {
return id;
}
#Override
public String toString() {
return "Triangle ID: " + getID()
+ " Area: " + calculateArea();
}
#Override
public int compare(Triangle t1, Triangle t2) {
if (t1.calculateArea() > t2.calculateArea()) {
return 1;
} else if (t1.calculateArea() < t2.calculateArea()) {
return -1;
} else {
return 0;
}
}
}
Java does not allow instantiation of abstract class directly for itself.
Can we instantiate an abstract class?
Create an abstract class called Shape -> it contains an abstract method calculateArea.
Then triangle can extend this class to become an concrete implementation. Then you can instantiate objects from it.

toString not outputting, simple hierarchy class program

I have two interfaces and two classes, Order class is parent of CoffeeBagOrder, There is no compiler error it just isn't displaying and I can't see why not
Order class:
public abstract class Order implements OrderInterface {
//variables
final static double SALES_TAX = 0.1; //not initialised by constructor
int unitWeight, numberOfUnits;
public Order() {
unitWeight=0;
numberOfUnits=0;
}
public Order(int unitWeight, int numberOfUnits) {
unitWeight=unitWeight;
numberOfUnits=numberOfUnits;
}
public void numberOfItems(int number) {
numberOfUnits=number;
}
public void unitWeight(int weight) {
unitWeight=weight;
}
}
CoffeeBagOrder class
public class CoffeeBagOrder extends Order implements Sales {
final static double PRICE_PER_KG = 5.55;
double salesBeforeTax;
double tax;
double totalSales;
public CoffeeBagOrder() {
}
public CoffeeBagOrder(int unitWeight, int numberOfUnits) {
super(unitWeight,numberOfUnits);
}
public double calculateSalesBeforeTax() {
salesBeforeTax= unitWeight*numberOfUnits*5.50;
return salesBeforeTax;
}
public double calculateSalesTax() {
tax=salesBeforeTax*0.10;
return tax;
}
public double calculateTotalSales() {
totalSales=salesBeforeTax+tax;
return totalSales;
}
//Override
public String toString() {
return "Price before tax: "+calculateSalesBeforeTax()+"\nTax: "+calculateSalesTax()+"\nTotal price: "+calculateTotalSales();
}
}
main
import java.util.Scanner;
public class Tester {
public static void main (String[] args) {
Scanner sc= new Scanner(System.in);
System.out.print("Enter number of bags sold: ");
int unitWeight=sc.nextInt();
System.out.print("Enter weight of bags in kilograms: ");
int numberOfUnits=sc.nextInt();
CoffeeBagOrder customer=new CoffeeBagOrder(unitWeight,numberOfUnits);
customer.toString();
}
}
I have omitted the interfaces but they are followed accordingly , thanks in advance, also I am unsure if I have efficiently written the constructors as they are both the same?
Change your Order class constructor like below (check this.):
public Order(int unitWeight, int numberOfUnits) {
this.unitWeight=unitWeight;
this.numberOfUnits=numberOfUnits;
}
You were not updating class field in constructor! It was assigning the parameter to itself.
And modify toString in CoffeeBagOrder like below (check annotation):
#Override
public String toString() {
return "Price before tax: "+calculateSalesBeforeTax()+"\nTax: "+calculateSalesTax()+"\nTotal price: "+calculateTotalSales();
}
Always use #Override annotation when you intend to override, to take it effect, which is best practice rather than calling toString() explicitly.
And print using
System.out.println(customer);

count the number of objects created by java

I'm trying to count the number of objects created but it always returns 1.
public class Drivertwo {
public static void main(String[] args) {
Employee newEmp = new Employee();
Employee newEmp2 = new Employee();
Calculate newcal = new Calculate();
Clerk newclerk = new Clerk();
float x;
int y;
newEmp.setEmp_no(2300);
newEmp.setEmp_name("W.Shane");
newEmp.setSalary(30000);
newEmp.counter();
newEmp2.setEmp_no(1300);
newEmp2.setEmp_name("W.Shane");
newEmp2.setSalary(50000);
newEmp2.counter();
newclerk.setEmp_name("Crishane");
newclerk.setEmp_no(1301);
newclerk.setGrade(2);
newclerk.setSalary(45000);
newclerk.counter();
System.out.println("Salary is:" + newcal.cal_salary(newclerk.getSalary(), newclerk.getEmp_no()));
System.out.println("Name is:" + newclerk.getEmp_name());
System.out.println("Employee number is:" + newclerk.getEmp_no());
System.out.println("Employee Grade is:" + newclerk.getGrade());
System.out.println("No of objects:" + newEmp.numb);
This is my class with the main method
public class Employee {
private int salary;
private int emp_no;
private String emp_name;
public int numb=0;
public int getSalary() {
return salary;
}
public int getEmp_no() {
return emp_no;
}
public String getEmp_name() {
return emp_name;
}
public void setSalary(int newSalary) {
salary = newSalary;
}
public void setEmp_no(int newEmp_no) {
emp_no = newEmp_no;
}
public void setEmp_name(String newEmp_name) {
emp_name = newEmp_name;
}
}
public int counter() {
numb++;
return numb;
This is my Employee class
I tried to run counter in my employee class as a starter but it always returns 1. I know I can make a counter in main class and everytime I make a new object I can get the counter but I want to automatically increase the numb by 1 when an object is made.
You need to make numb static so that there will only be one copy for every instance of the class. As it is, every single Employee object has its own copy of numb.
Also instead of creating a method to up the counter why not just put it in the constructor:
public Employee() {
numb++;
}
numb is an instance variable, meaning that each Employee object will have its own numb, that will be initialized by 0.
If you want all the Employee instances to share the same numb, you should make it static.
// Java program Find Out the Number of Objects Created
// of a Class
class Test {
static int noOfObjects = 0;
// Instead of performing increment in the constructor instance block is preferred
//make this program generic. Because if you add the increment in the constructor
//it won't work for parameterized constructors
{
noOfObjects += 1;
}
// various types of constructors
public Test()
{
}
public Test(int n)
{
}
public Test(String s)
{
}
public static void main(String args[])
{
Test t1 = new Test();
Test t2 = new Test(5);
Test t3 = new Test("Rahul");
System.out.println(Test.noOfObjects);
}
}
Since static members initialized only once and it will be same for each and every instances of class.
class YourClass {
private static int numb;
public YourClass() {
//...
numb++;
}
public static int counter() {
return numb;
}
}
So simple;-
make this modifications
make numb static like, public int numb=0;,
remove numb++; from method count() and
create constructor public Employee{numb++;}

method does not override or implement a method from a supertype #override compile error

I'm getting an error method does not override or implement a method from a supertype #Override. I want to print "cannot change capacity of a car" after it prints one car. I need to override the setCapacity to print this other part. I believe the code is mostly correct, just not sure why it's not correctly override the setCapacity method. The final output is:
New capacity = 1600
Vehicle Info:
capacity = 1600cc
make = Mazda
Cannot change capacity of a car
Vehicle Info:
capacity = 1200cc
make = Holden
type = sedan
model = Barina
My code is:
class Vehicle { // base class
public void setCapacity(int setCapacity) {
this.capacity = setCapacity;
System.out.println("New Capacity = " + setCapacity);
}
int capacity;
String make;
Vehicle(int theCapacity, String theMake) {
capacity = theCapacity;
make = theMake;
}
void print() {
System.out.println("Vehicle Info:");
System.out.println(" capacity = " + capacity + "cc" );
System.out.println(" make = " + make );
}
}
class Car extends Vehicle {
public String type;
public String model;
public Car(int theCapacity, String theMake, String theType, String theModel) {
super(theCapacity, theMake);
type = theType;
model = theModel;
}
#Override
public void print() {
super.print();
System.out.println(" type = " + type);
System.out.println(" model = " + model);
}
#Override
public void setCapacity() {
super.print();
System.out.println("Cannot change capacity of a car");
}
}
class Task3 {
public static void main (String[]args){
Car car1 = new Car (1200,"Holden","sedan","Barina" );
Vehicle v1 = new Vehicle (1500,"Mazda");
v1.setCapacity(1600);
v1.print();
car1.setCapacity(1600);
car1.print();
}
}
There is a mismatch in the child and parents method signature of setCapacity(). If you want to override a method from the parent class in the child class then it must have the same signature.
Change
public void setCapacity() { //... }
to
public void setCapacity(int setCapacity) { // ... }
in the Car class.
In your code you have missed the parameter setCapacity and thus the compiler complains.
The signature of createCapacity is different in Vehicle and Car classes. So, there is a compilation error. In Vehicle class you have an argument setCapacity but in the Car class the argument list to the method is empty. So, overriding is not possible.
#Override
public void setCapacity( int capacity ) { --> **adding this argument here will fix the issue.**
super.print();
System.out.println("Cannot change capacity of a car");
}
public void setCapacity(int setCapacity) {
this.capacity = setCapacity;
System.out.println("New Capacity = " + setCapacity);
}
The void setCapacity(int setCapacity) is not overriden. void setCapacity() and void setCapacity(int setCapacity) are two different methods. Therefore generates the #Overrideannotation the compile error.
Regarding the terminology, the setCapacity is said to be overloaded in this scenario.

How to write a method that returns an instance of an abstract class?

I am a beginner in Java and i trying to understand the abstract classes.
Below is the code that I've written; the question is: how do i write a method that will return an instance of that class.
public abstract class VehicleEngine
{
protected String name;
protected double fabricationCons;
protected double consum;
protected int mileage;
public VehicleEngine(String n, double fC)
{
name = n;
fabricationCons = fC;
mileage = 0;
consum = 0;
}
private void setFabricationCons(double fC)
{
fabricationCons = fC;
}
public abstract double currentConsum();
public String toString()
{
return name + " : " + fabricationCons + " : " + currentConsum();
}
public void addMileage(int km)
{
mileage += km;
}
public double getFabricationConsum()
{
return fabricationCons;
}
public String getName()
{
return name;
}
public int getMileage()
{
return mileage;
}
//public VehicleEngine get(String name){
//if(getName().equals(name)){
//return VehicleEngine;
//}
//return null;
//}
}
public class BenzinVehicle extends VehicleEngine
{
public BenzinVehicle(String n, double fC)
{
super(n, fC);
}
#Override
public double currentConsum()
{
if (getMileage() >= 75000) {
consum = getFabricationConsum() + 0.4;
} else {
consum = getFabricationConsum();
}
return consum;
}
}
public class DieselVehicle extends VehicleEngine
{
public DieselVehicle(String n, double fC)
{
super(n, fC);
}
#Override
public double currentConsum()
{
int cons = 0;
if (getMileage() < 5000) {
consum = getFabricationConsum();
} else {
consum = getFabricationConsum() + (getFabricationConsum() * (0.01 * (getMileage() / 5000)));
}
return consum;
}
}
This is the main.
public class Subject2
{
public static void main(String[] args)
{
VehicleEngine c1 = new BenzinVehicle("Ford Focus 1.9", 5.0);
DieselVehicle c2 = new DieselVehicle("Toyota Yaris 1.4D", 4.0);
BenzinVehicle c3 = new BenzinVehicle("Citroen C3 1.6",5.2);
c1.addMileage(30000);
c1.addMileage(55700);
c2.addMileage(49500);
c3.addMileage(35400);
System.out.println(c1);
System.out.println(c2);
System.out.println(VehicleEngine.get("Citroen C3 1.6")); //this is the line with problems
System.out.println(VehicleEngine.get("Ford Focus "));
}
}
And the output should be:
Ford Focus 1.9 : 5.0 : 5.4
Toyota Yaris 1.4D : 4.0 : 4.36
Citroen C3 1.6 : 5.2 : 5.2
null
You can not return an instance of an abstract class, by definition. What you can do, is return an instance of one of the concrete (non-abstract) subclasses that extend it. For example, inside the VehicleEngine you can create a factory that returns instances given the type of the instance and the expected parameters, but those instances will necessarily have to be concrete subclasses of VehicleEngine
Have a look at the Factory Method pattern. Your concrete classes will implement an abstract method that returns a class instance.
Abstract classes do not keep a list of their instances. Actually no Java class does that. If you really want to do that, you could add a static map to VehicleEngine like this:
private static Map<String, VehicleEngine> instanceMap = new HashMap<String, VehicleEngine>();
and change your get method to a static one like this:
public static VehicleEngine get(String name) {
return instanceMap.get(name);
}
and add this line to the end of the constructor of VehicleEngine:
VehicleEngine.instanceMap.put(n, this);
this way every new instance created puts itself into the static map. However this actually is not a good way to implement such a functionality. You could try to use a factory to create instances, or you could consider converting this class into an enum if you will have a limited predefined number of instances.

Categories