I am trying to practice with Polymorphism and using classes. I wrote a superclass called Card. I then wrote 3 subclasses called: IDCard, CallingCard, and DriverLicense. I then wrote another class called Billfold which is supposed to contain slots for two of the cards.
I am supposed to write a BillfoldTester program which adds two objects of different subclasses to a Billfold object.
In BillfoldTester, a DriverLicense object and a CallingCard object are instantiated and added to a Billfold, which refers to these objects with Card references.
I don't really understand how to do this. I created two Card objects but I am trying to add it to my Billfold and it wont work. I tried Billfold a = new Card (x); but it's not right... Any help is much appreciated.
public class BillfoldTester
{
public static void main (String[]args)
{
Card x= new IDCard("Julie", 1995);
Card j= new DriverLicense("Jess", 1997);
//Having trouble trying to put the objects into my Billfold and print it.
}
}
public class Billfold extends Card
{
private String card1;
private String card2;
void addCard(String Card)//Not sure if this should be String
{
card1=Card;
}
}
public class Card
{
private String name;
public Card()
//This is my superclass
{
name = "";
}
public Card(String n)
{
name = n;
}
public String getName()
{
return name;
}
public boolean isExpired()
{
return false;
}
public String format()
{
return "Card holder: " + name;
}
}
public class IDCard extends Card
{
//This is one of my subclasses
private int IDNumber;
public IDCard (String n, int id)
{
super(n);
this.IDNumber=id;
}
public String format()
{
return super.format() + IDNumber;
}
}
The polymorphism example. Not sure if the functionally is exactly what you need, but you can see the whole idea (I hope). See the showAllFormat() method of Billfold class.
The whole point is inside different format() methods of the DriverLicense and IDCard. Depending on the 'real' (or initially assigned) object the different method will be called even if you just only refer to 'Card' class.
NOTE:
You didn't provide your DriverLicense implementation, and my is just from head. I have a bit different constructor to show this sub-classes may be totally different.
import java.util.ArrayList;
import java.util.List;
class Billfold {
List<Card> list = new ArrayList<Card>(10);
void addCard(Card card) // Q: Not sure if this should be String
// A: You would like to add a Card
{
list.add(card);
}
void showAllFormat() {
// go polymorphism !...
// when you call this general 'format()' you see the subclasses
// 'format()' is executed, not from 'Card' class
for(Card x: list) {
System.out.println(x.format());
}
}
}
class Card {
private String name; /* owner */
public Card() //This is my superclass
{
name = "";
}
public Card(String n) {
name = n;
}
public String getName() {
return name;
}
public boolean isExpired() {
return false;
}
public String format() {
return "Card holder: " + name;
}
}
class IDCard extends Card {
//This is one of my subclasses
private int IDNumber;
public IDCard(String n, int id) {
super(n);
this.IDNumber = id;
}
public String format() {
return "(ID)" + super.format() + " " + IDNumber;
}
}
class DriverLicense extends Card {
private String type;
public DriverLicense(String n, String type) {
super(n);
this.type = type;
}
public String format() {
return "(DL)" + super.format() + " TYPE: " + type;
}
}
public class BillfoldTester {
public static void main(String[] args) {
Card x = new IDCard("Julie", 1995);
Card j = new DriverLicense("Jess", "AB");
Billfold bf = new Billfold();
bf.addCard(x);
bf.addCard(j);
bf.showAllFormat();
}
}
This is wrong. A Billfold is not a Card; it HAS Cards.
public class Billfold
{
List<Card> cards = new ArrayList<Card>();
void addCard(Card card) {
if (card != null) {
this.cards.add(card);
}
}
}
Prefer composition over inheritance.
You should have Billfold class have two Card objects, not two Strings:
public class Billfold
{
Card card1;
Card card2;
void addCard(Card card) {
if (card != null) {
if (card1 != null) {
this.card1 = card;
} else {
this.card2 = card;
}
}
}
Ok, you're largely on the right track, just a couple of things:
void addCard(String Card)//Not sure if this should be String
{
card1=Card;
}
You're right, this should be:
void addCard(Card card)
{
card1=card;
}
then to add them:
public class BillfoldTester
{
public static void main (String[]args)
{
Card x= new IDCard("Julie", 1995);
Card j= new DriverLicense("Jess", 1997);
Billfold bf = new Billfold();
Billfold.addCard(x);
Billfold.addCard(j);
}
}
Then add a method to Billfold to print the cards in it.
Edit: Oh yeah, and duffymo is totally right, you don't need to extends Card on Billfold
Related
I need to make a programm which is like a rally, theres 2 types of vehicles, motorcycle and cars, two types of motorcycle, with and without sidecar, the thing is that I need to verify if there is just a motorcycle in an array list, I mean, two wheels vehicle. That verification should be done in a method called esDe2Ruedas(), which is called by an abstract overrided method called check() that should be the one that verifies if a group of vehicles from an array are able to run in the rally, if its true all the elements of the array must be from the same type.
Here is the code
this is how the program arrays the vehicles
GrandPrix gp1 = new GrandPrix();
gp1.agregar(v1);
//gp1.mostrar(v1);
gp1.agregar(v2);
System.out.println(gp1.check());
GrandPrix gp2 = new GrandPrix();
gp2.agregar(vt1);
gp2.agregar(vt2);
gp2.agregar(m2);
System.out.println(gp2.check());
GrandPrix gp3 = new GrandPrix();
gp3.agregar(vt1);
gp3.agregar(vt2);
gp3.agregar(m1);
System.out.println(gp3.check());
GrandPrix gp4 = new GrandPrix();
gp4.agregar(m1);
gp4.agregar(m2);
System.out.println(gp4.check());
This is the class that is using
import java.util.ArrayList;
public class GrandPrix extends Rally{
ArrayList<Vehiculo> ve = new ArrayList<Vehiculo>();
public void agregar(Vehiculo v) {
ve.add(v);
}
public void agregar(Carro c) {
ve.add(c);
}
public void agregar(Moto m) {
ve.add(m);
}
#Override
boolean check() {// HERE I VERIFY IF THE VEHICLES ARE COMPATIBLE
return false;
}
}
This is the class where everything goes on
public class Vehiculo {
private String Nombre;
private double velocidad_max;
private int peso;
private int comb;
public Vehiculo() {
setNombre("Anónimo");
setVel(130);
setPeso(1000);
setComb(0);
}
public Vehiculo(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
}
double rendimiento() {
return velocidad_max/peso;
}
public boolean mejor(Vehiculo otroVehiculo) {
return rendimiento()>otroVehiculo.rendimiento();
}
public String toString() {
return getNombre()+"-> Velocidad máxima = "+getVel()+" km/h, Peso = "+getPeso()+" kg";
}
/**************************************
---------SET And GET Nombre------------
***************************************/
public String getNombre() {
return Nombre;
}
public void setNombre(String nuevoNombre) {
this.Nombre=nuevoNombre;
}
/**************************************
---------SET And GET velocidad_max------------
***************************************/
public double getVel() {
return velocidad_max;
}
public void setVel(double nuevaVel) {
this.velocidad_max=nuevaVel;
}
/**************************************
---------SET And GET peso------------
***************************************/
public double getPeso() {
return peso;
}
public void setPeso(int nuevoPeso) {
this.peso=nuevoPeso;
}
/**************************************
---------SET And GET comb------------
***************************************/
public int getComb() {
return comb;
}
public void setComb(int comb) {
this.comb = comb;
}
boolean esDe2Ruedas() {
return false;
}
}
This is the class of motorcycles, which is in theory the same as the car's class, without sidecar thing
public class Moto extends Vehiculo{
private boolean sidecar;
public Moto(String string, double d, int i, int j) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(false);
}
public Moto(String string, double d, int i, int j, boolean b) {
setNombre(string);
setVel(d);
setPeso(i);
setComb(j);
setSidecar(b);
esDe2Ruedas(false);
}
public String toString() {
String str = null;
if(isSidecar())
str =super.toString()+", Moto, con sidecar";
else
str =super.toString()+", Moto";
return str;
}
public boolean isSidecar() {
return sidecar;
}
public void setSidecar(boolean sidecar) {
this.sidecar = sidecar;
}
I guess what you presented is what is given. If you came up with the design it is ok, but I believe it could be improved. Anyway, I try to respond to what I believe was your question straight away.
Vehiculo is the super type of Moto (which can have a side car and becomes 3 wheeler).
Vehiculo has a method esDe2Ruedas, which returns false.
Moto inherits that method <-- this is wrong, it should override it and, depending on side car, return the expected boolean value.
In the check method you can now distinguish between Moto and "Moto with sidecar" by using that method.
i am trying to write a class which has an array of a subclass in the same project, and when i am trying to write a method that will add a new object to the array on condition that this object is not already in the array, and also if the specific cell is free, so the object will enter to the array.
but the problem is that i need to insert a variable to this method which is the copy constructor's object.
the problem is that in the subclass i don't know how to write the copy constructor.
so i will give a short example of 2 classes and you will show me how to write a copy constructor with them :
public class Food
{
private String _foodName;
public Food(String foodName)
{
_foodName=foodName;
}
public String getFoodName()
{
return _foodName;
}
public void showName()
{
System.out.println("The food's name is: " +_getFoodName());
}
}
public class Apple extends Food
{
private int _numOfApples;
public Apple(String name, int numOfApples)
{
super(name);
_numOfApples=numOfApples;
}
public Apple(Apple other)
{
????
}
}
how does the copy constructor should looks like ?
thank you for your help :)
By invoking the other constructor. Like,
public Apple(Apple other) {
this(other.getFoodName(), other._numOfApples);
}
I cannot help you properly because i cannot understand entirely what you are trying to do but at least i can help you correct some mistakes in your code:
public class Food
{
private String food;
public Food(String foodName)
{
food = foodName;
}
public String getFoodName()
{
return food;
}
public void showName()
{
System.out.println("The food's name is: " + getFoodName());
}
}
public class Apple extends Food
{
private int numOfApples;
public Apple(String name, int numberOfApples)
{
super(food);
numOfApples=numberOfApples;
}
public Apple(Apple copy)
{
this.name = copy.name;
this.numOfApples = copy.numOfApples;
}
}
Hope this helps.
I am trying to sort an ArrayList in increasing order in reference to a certain variable. This is the problem question.
q5: Create a public class named Snow with private instance variables vast, prior, ethnic, and remarkable each of type int. You may add any other methods and variables you'd like to this class.
Outside of Snow (in the Problem Set class) write a public static method named sortSnow that takes an ArrayList of Snows as a parameter and returns void. This method will sort the input by the variable remarkable in increasing order
This is what I wrote.
public class snow implements Comparable<snow> {
private int vast;
private int prior;
private int ethnic;
private int remarkable;
public snow( int vast , int prior, int ethnic ,int remarkable) {
this.vast=vast;
this.prior = prior;
this.ethnic = ethnic;
this.remarkable = remarkable;
}
public int getEthnic() {
return ethnic;
}
public void setEthnic(int ethnic) {
this.ethnic = ethnic;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
public int getVast() {
return vast;
}
public void setVast(int vast) {
this.vast = vast;
}
public int getRemarkable() {
return remarkable;
}
public void setRemarkable(int remarkable) {
this.remarkable = remarkable;
}
public int compareTo(snow compareSnow) {
// TODO Auto-generated method stub
int compareThese = ((snow) compareSnow).getRemarkable();
//ascending order
return this.remarkable - compareThese;
}
}
public static void sortSnow(ArrayList<snow>input){
Collections.sort(input);
}
I am not understanding what the error means. The autolab is giving me this error:
Could not find class submission.ProblemSet$Snow
Java is case sensitive i.e. snow is not Snow is not sNoW. Rename your class to Snow and try again. Also, it is ArrayList and not arraylist.
Then to sort a List, you can use Collections.sort.
I think this is you want to achieve
Save below code in file called "Snow.java" compile it and try to run it.
import java.util.ArrayList;
import java.util.Collections;
//As ".java" file can contain only single public java class
//I made Problem set class non-public so we can use its main method
//to run and see output
class ProblemSet {
public static void main(String[] args) {
Snow one = new Snow(1,1,1,1);
Snow two = new Snow(1,1,1,2);
Snow three = new Snow(1,1,1,3);
Snow four = new Snow(1,1,1,4);
Snow five = new Snow(1,1,1,5);
Snow six = new Snow(1,1,1,6);
ArrayList arrayList = new ArrayList();
arrayList.add(one);
arrayList.add(three);
arrayList.add(five);
arrayList.add(two);
arrayList.add(six);
arrayList.add(four);
System.out.println("Without sort");
System.out.println(arrayList);
sortSnow(arrayList);
System.out.println("With sort");
System.out.println(arrayList);
}
//this is your static method which takes argument as array list of Snow
//And it applies sorting logic based on compareTo method which you wrote
//in Snow class. As per java best practice Class name should start with
//Upper case letters and follow camel casing I renamed your class from
//"snow" to "Snow"
public static void sortSnow(ArrayList<Snow> input){
Collections.sort(input);
}
}
//This is you public class Snow
//If you want to keep it in separate java file put it
public class Snow implements Comparable<Snow> {
private int vast;
private int prior;
private int ethnic;
private int remarkable;
public Snow(int vast, int prior, int ethnic, int remarkable) {
this.vast = vast;
this.prior = prior;
this.ethnic = ethnic;
this.remarkable = remarkable;
}
public int getEthnic() {
return ethnic;
}
public void setEthnic(int ethnic) {
this.ethnic = ethnic;
}
public int getPrior() {
return prior;
}
public void setPrior(int prior) {
this.prior = prior;
}
public int getVast() {
return vast;
}
public void setVast(int vast) {
this.vast = vast;
}
public int getRemarkable() {
return remarkable;
}
public void setRemarkable(int remarkable) {
this.remarkable = remarkable;
}
public int compareTo(Snow compareSnow) {
// TODO Auto-generated method stub
int compareThese = ((Snow) compareSnow).getRemarkable();
//ascending order
return this.remarkable - compareThese;
}
//This is added because when you use array list to print
//it will print remarkable of particular Snow object
#Override
public String toString() {
return String.valueOf(remarkable);
}
}
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.
I am trying to add weapons to a player inventory. It's kind of hard to explain, so I'll try my best. What I have are a class for each weapon, a class for Combat, and a class for the Player. I am trying to get it to where when the Random number equals a certain number, it will add a weapon to the player inventory. I will put my code Below.
Combat Class:
public class Combat {
M4 m4 = new M4();
M16 m16 = new M16();
M9 m9 = new M9();
Glock glock = new Glock();
SCAR Scar = new SCAR();
Player player = new Player();
final int chanceOfDrop = 3;
static boolean[] hasWeapon = {false, true};
public static int ranNumberGen(int chanceOfDrop) {
return (int) (Math.random()*5);
}
private void enemyDead() {
boolean canDrop = false;
if(ranNumberGen(chanceOfDrop)==0){
canDrop = true;
}
if(canDrop == true){
if(ranNumberGen(0) == 1) {
Player.addInvetory(m4.weaponName(wepName), m4.weaponAmmo(wepAmmo)); //Issues here. wepName & wepAmmo cannot be resolved into variable
//Should I just delete the line?
//Trying to get it to add the weapon M4 to the player inventory.
//Maybe use an ArrayList? If so I need a couple pointers on how to implement this.
}
}
}
}
M4 Class:
public class M4 implements Armory {
//Weapon classes are practically identical except for differences in the name wepDamage and wepAmmo.
public Integer weaponAmmo(int wepAmmo) {
wepAmmo = 10;
return wepAmmo;
}
public Integer weaponDamage(int wepDamage) {
wepDamage = 5;
return wepDamage;
}
public String weaponName(String wepName) {
wepName = "M4";
return wepName;
}
Player Class:
public class Player {
public static int health = 100;
//Player Class.
public static void addInvetory(String wepName, int wepAmmo) {
Player.addInvetory(wepName, wepAmmo);
}
public static void removeInventory(String wepName, int wepAmmo) {
Player.addInvetory(wepName, wepAmmo);
}
public static void removeAll(String wepName, int wepAmmo) {
Player.removeAll(wepName, wepAmmo);
}
Interface:
public interface Armory {
//Interface implemented by all of the weapons classes.
public Integer weaponAmmo(int wepAmmo);
public Integer weaponDamage(int wepDamage);
public String weaponName(String wepName);
Hope you can help!
class Weapon {
private final String name;
private final int damage;
private final int ammo;
public Weapon(final String name,final int damage,final int ammo) {
this.name = name;
this.damage = damage;
this.ammo = ammo;
}
public Weapon clone() {
return new Weapon(this.name,this.damage,this.ammo);
}
public String getName() {
return this.name;
}
public int getAmmo() {
return this.ammo;
}
public int getDamage() {
return this.damage;
}
}
class WeaponFactory {
static WeaponFactory factory;
public static WeaponFactory getWeaponFactory() {
if(factory == null) {
factory = new WeaponFactory();
}
return factory;
}
private ArrayList<Weapon> weapons = new ArrayList<Weapon>();
private Random random;
private WeaponFactory() {
//TODO: Fix Ammo and Damage
weapons.add(new Weapon("M4",0,0));
weapons.add(new Weapon("M16",0,0));
weapons.add(new Weapon("M9",0,0));
weapons.add(new Weapon("Glock",0,0));
weapons.add(new Weapon("SCAR",0,0));
}
public Weapon getWeapon() {
int w = random.nextInt(weapons.length);
return weapons.get(w).clone();
}
}
class Combat {
...
private void enemyDead() {
if(ranNumberGen(chanceOfDrop)==0){
Player.addInventory(WeaponFactory.getWeaponFactory().getWeapon());
}
}
}
You can use an array of Armory and the generate a random number from 0 to the size of the array as an index to the array to decide which weapon to add.
Okay dude, since your question about creating a programming language was closed, I'm answering it through here:
I think that your idea is great! Don't give up on it, yet don't get too excited. I would try all the options that you have heard of(interpreted route AND the Compiled route). If you can get either of those to work, then you may proceed to go into further detail with the language creation. It's going to take a while though. Be patient!