Super class is not functioning, as when the Steelfactory class try's to get the data from the super class, the output shows that there is noting there.
Looking to solves as to why this might be happening.
The Factory called null with 0makes cars at a rate of 0since the year 1998
I am wondering if it is due to, having called my super class wrong, but I did not gain any errors when writing it. Or could there there be another issue in the code logic wise?
The code:
package finalsproject;
static abstract class Factory {
//Atributes:
String factoryName; //The name of the factory
int employeeAmount; // number of workers in the factory
int producedAmount; // number of products made
// Constructor:
public Factory (String ifactoryName,int iemployeeAmount,int iproducedAmount) {// Prameterized consrtuctor
factoryName = ifactoryName;
employeeAmount = iemployeeAmount;
producedAmount = iproducedAmount;
}
//Methods:
public abstract String getFactoryName();
public abstract int getEmployeeAmount();
public abstract int getProducedAmount();
}
//The class SteelFactory must have the following specifications
//-It must implement the abstract class Factory
//Make these two classes implement the abstract class above
static class SteelFactory extends Factory {
//Attributes:
String factoryName; // Name of the factory
int employeeAmount; // Number of workers
int producedAmount; // number of products
int yearCreated; // the year the factory was made
//Constructor:
public SteelFactory (String ifactoryName,int iemployeeAmount,int iproducedAmount,int iyearCreated) {
super ( ifactoryName, iemployeeAmount,iproducedAmount);
yearCreated = iyearCreated;
}
// Methods
public String getFactoryName() {
return (factoryName);
}
public int getEmployeeAmount() {
return (employeeAmount);
}
public int getProducedAmount() {
return (producedAmount);
}
public String toString () {
return ("The Factory called " + factoryName + " with " + employeeAmount + "makes cars at a rate of " + producedAmount + "since the year "+ yearCreated);
}
}
You can resolve this by simply removing the duplicate variables factoryName, employeeAmount and producedAmount from your SteelFactory class, otherwise the class will use the local variables that were never initialized instead of the correct variables from the super class. One big reason for extending a class is so that we don't have to re-use/re-type the same variables and methods in multiple classes.
Also, don't forget to use #Override annotation, it helps you keep track of which methods have been extended and helps prevent common mistakes.
Working code as follows:
static class SteelFactory extends Factory {
//Attributes:
int yearCreated; // the year the factory was made
//Constructor:
public SteelFactory (String ifactoryName,int iemployeeAmount,int iproducedAmount,int iyearCreated) {
super ( ifactoryName, iemployeeAmount,iproducedAmount);
yearCreated = iyearCreated;
}
// Methods
#Override
public String getFactoryName() {
return (factoryName);
}
#Override
public int getEmployeeAmount() {
return (employeeAmount);
}
#Override
public int getProducedAmount() {
return (producedAmount);
}
#Override
public String toString () {
return ("The Factory called " + factoryName + " with " + employeeAmount + "makes cars at a rate of " + producedAmount + "since the year "+ yearCreated);
}
}
Then simply use:
SteelFactory test = new SteelFactory("Test", 78, 26, 2022);
System.out.println(test.toString());
Will correctly print the following result (You'll need to fix your formatting to include spaces):
The Factory called Test with 78makes cars at a rate of 26since the year 2022
Related
So I have this assignment which I need to put data into a tree set. I have three classes they are :
Brother.java. The assignment said the constructor is not public, so I'm using the getInstance() to initialize Brother object
public class Brother {
String name;
int day;
int month;
private static Brother instance = null;
private Brother()
{
name = "0";
day = 0;
month = 0;
}
public static Brother getInstance()
{
if(instance == null)
{
instance = new Brother();
}
return instance;
}
}
Family class. This class is used to assign the brother object into the tree set with Brother as the objects.
import java.util.Set;
import java.util.TreeSet;
public class Family {
Set<Brother> Brothers;
public Family()
{
this.Brothers = new TreeSet<Brother>();
}
public Brother makeBrother()
{
Brother B = Brother.getInstance();
return B;
}
public boolean addBrother(String name, int day, int month)
{
Brother B = Brother.getInstance();
return Brothers.add(B);
}
}
And finally the main class
public class Main {
public static void main(String[] args) {
Family myFamily = new Family();
myFamily.makeBrother();
// myFamily.addBrother("Shane", 3, 2);
}
}
whenever I try to use myFamily.addBrother() I always got this error "Exception in thread "main" java.lang.ClassCastException: class Brother cannot be cast to class java.lang.Comparable (Brother is in unnamed module of loader 'app'; java.lang.Comparable is in module java.base of loader 'bootstrap')". What do I have to do with that? The program is perfectly fine when I use myFamily.makeBrother(). This algorithm is not all done yet but when I try to run it this happened to me and I cannot continue to the next step. Thank you before.
You are using a Set instead of a List because you want to avoid duplicates. To know which Brothers are duplicate, a TreeSet needs either a comparator, or the objects themselves need to implement Comparable.
Read the javadoc of TreeSet for more: https://docs.oracle.com/javase/7/docs/api/java/util/TreeSet.html
BTW that getInstance always returns the same instance. You'll probably need to change that to createInstance or something that actually creates new ones.
I agree with #GreyFairer, you have to provide a comparator in order to use Set, see this example:
Class Cast Exception problems with TreeSet
I hope it can helps you!
I see a few problems there.
You have defined Brother as a singleton. That means only one Brother instance will exist in your program. So all references to Brother will point to the same instace. I would avoid singleton for this class since doesn't makes sense.
If you what to use a TreeSet (without providing a Comparator for the Tree) then Brother must implement Comparable
Family.makeBrother just return the singleton Brother, but does not add it to the family tree, that's why you don't get the error.
This is a working rework of your code
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class FamilyTreeSet {
public static void main(String[] args) {
Family myFamily = new Family();
myFamily.addBrother("Shane", 3, 2);
myFamily.addBrother("Bob", 2, 4);
System.out.println(myFamily);
}
public static class Brother implements Comparable<Brother>{
private String name;
private int day;
private int month;
public Brother(String name, int day, int month) {
this.name = name;
this.day = day;
this.month = month;
}
public String getName() {
return name;
}
public int getDay() {
return day;
}
public int getMonth() {
return month;
}
#Override
public int compareTo(Brother o) {
return Comparator.comparing(Brother::getName, String.CASE_INSENSITIVE_ORDER).compare(this, o);
}
#Override
public String toString() {
return "Brother{" +
"name='" + name + '\'' +
", day=" + day +
", month=" + month +
'}';
}
}
public static class Family {
Set<Brother> Brothers;
public Family()
{
this.Brothers = new TreeSet<Brother>();
}
public boolean addBrother(String name, int day, int month)
{
Brother B = new Brother(name, day, month);
return Brothers.add(B);
}
#Override
public String toString() {
return "Family{" +
"Brothers=" + Brothers +
'}';
}
}
}
I'm using the each brother's name to compare brothers. Check that I first add Shane but in the output Bob goes first. If you want to compare brothers by birthday just change the compareTo.
Family{Brothers=[Brother{name='Bod', day=2, month=4}, Brother{name='Shane', day=3, month=2}]}
Here is my code
class Bomb {
static String description = "bomb description";
static int id = 1;
private String name;
private int size;
public static void Bomb() {
id++;
System.out.println(" " + description + " " + id);
}
public void setName(String name) {
this.name = name;
}
public void setSize(int size) {
this.size = size;
}
public void printout() {
System.out.println(" " + name + size);
}
}
public class array {
public static void main(String args[]) {
Bomb.Bomb();
Bomb detenator = new Bomb();
Bomb destroyer = new Bomb();
destroyer.setName("hr4");
destroyer.setSize(43);
detenator.setName("m1s");
detenator.setSize(34);
detenator.printout();
destroyer.printout();
}
}
I want the description to print with each bomb object. but the description prints by itself.
any one got any idea how to fix that?
also please suggest any alternative ways I could've written this code, but don't make it to complicated. i just started learning java so i probably wont understand complex stuff.
I short, there are no "static constructors".
You may want something that references a static member, like this:
public Bomb() {
id++;
System.out.println(" " + Bomb.description + " " + id);
}
Please go over the Java tutorial of constructors:
Constructor declarations look like method declarations—except that they use the name of the class and have no return type.
Your definition of constructor is completely messed up.
As #Reut Sharabani mentioned there is no something like static constructor. You are using constructors to initiate object of a class. And static let you use method just by calling ClassName.staticMethod() without creating object of the class (one ruling out another). If static constructor would exist you would be able to write something like, for example, ClassName.ClassName() which make no sense.
Constructors are not returning any value, so declaring them as void is an error. Again constructor is used to initialize your object with some values (but unnecessary)
I try to run a programm but i get those four errors.
TestCusomer.java:25: error: toString() in Invoice cannot override toString() in Object (same thing at line 49)
and
line 59 cannot find symbol . myCustomer.setTrn(112233778)
line 60 cannot find symbol . myCustomer.setPersentage(150)
My programm is the following:
class Invoice
{
int trn; //TAX REGISTRATION NUMBER
int persentage;
public Invoice{}
public int setTrn(int trn){
this.trn = trn;
}
public int getTrn(){
return trn;
}
public void setPersentage(int persentage){
this.persentage = persentage;
}
public int getPersentage(){
return persentage;
}
String toString(){
System.out.println(trn+" : "+persentage);
}
}
class Customer{
int trn;
int charging= 0;
public Customer(int trn){
this.trn = trn;
}
public int charge(int amount){
charging = charging + amount;
}
public int charge(int amount , int trn){
if (this.trn == trn){
charging = charging + amount;
}
}
String toString(){
System.out.println(trn+" : "+charging);
}
}
class TestCustomer
{
public static void main(String[] args){
Customer myCustomer = new Customer(112233778);
myCustomer.charge(100);
myCustomer.setTrn(112233778);
myCustomer.setPersentage(150);
System.out.println(myCustomer);
}
}
few things,
You need to declare the toString method public
You need to return a String in your toString methods
I strongly suggest you add the #Override notation when you override a method to ensure that you actually override the method
The cannot find symbol... happen because those methods are not defined in Customer, you have those in Invoice
Your toString() methods need to return String objects. You are outputting a string in them but not returning a string. Also make them public.
For example, your toString() method for the Invoice class should be:
public String toString()
{
return trn + " : " + persentage;
}
And for your second problem (cannot find symbols), those methods are in the Invoice class and not in the Customer class so they cannot be called on a Customer object.
So I'm building a game engine and I need to be able to call methods from a class that implements a certain interface(I only want to call methods implemented by the interface).
My problem is that I don't know what the class name will be implementing it.
So how does, for instance, Java call the run() method in all classes that implement Runnable without knowing the class name?
Really, you're asking about the Factory pattern or a dependency injection container such as Spring.
Of course you can call the methods on an interface, the question is how you get the instance. That of course has to be specified, coded or configured somewhere. Configuration is preferable if there could ever be more than one in the future.
Thus, more of a real example:
public interface MovementStrategy {
public Move selectMove (Actor actor, ActorSituation theirSituation);
}
public class MonsterTypes {
public static MonsterType GOBLIN = new MonsterType( "goblin", new AttackMover(1.2));
public static MonsterType TROLL = new MonsterType( "troll", new AttackMover(0.45));
public static MonsterType DEER = new MonsterType( "deer", new FleeMover(2.0));
// useful to have, also.
public static List<MonsterType> getAllRegisteredTypes();
public static class MonsterType {
protected String name;
protected MovementStrategy moveStrategy;
// TODO -- getters & setters for all properties.
// constructor.
public MonsterType (String name, MovementStrategy moveStrategy) {
this.name = name;
this.moveStrategy = moveStrategy;
}
}
}
public class AttackMover implements MovementStrategy {
// SPEC: generally move towards/attack PC, with varying speeds.
}
public class FleeMover implements MovementStrategy {
// SPEC: generally run away from PCs.
}
This isn't probably a perfect design -- it conflates "movement" (aka goal-seeking) with the actor's turn/actions overall -- but hopefully it gives you some more idea.
If you only want to call methods from the interface (good!), then you usually don't need to now the name of the implementor.
getRunnableFromSomewhere().run();
always works and calls the run() method on the instance that is returned by that method.
If you want to now the class name at runtime, simpy call getClass().getName() on the instance:
System.out.println(getRunnableFromSomewhere().getClass().getName());
A simple example with the Number interface:
public class NumberExample {
public static void main(String[] args) {
MagicNumber magic = MagicNumberProvider.get(); // a random implementation
System.out.println(magic.getMagicNumber().doubleValue()); // We know nothing about the implementations
}
}
class MagicNumberProvider {
public static MagicNumber get() {
return Math.random() > 0.5d ? new ItsMagicOne() : new ItsMagicTwo();
}
}
interface MagicNumber {
public Number getMagicNumber();
}
class ItsMagicOne implements MagicNumber {
#Override
public Number getMagicNumber() {return new Long(1);}
}
class ItsMagicTwo implements MagicNumber {
#Override
public Number getMagicNumber() {return new Double(2.5);}
}
It only calls interface methods and we have, from the perspective of the main method, no idea, which implementation of MagicNumber is used (it's random) and on which implementation of Number we actually call the doubleValue() method.
Service Provide Interface
You can use java SPI (Service Provider Interface) by which later implementing jars declare the same service in the manifest. A using app can do a lookup, iterate over them and pick one.
An example is the different XML parser implementations.
Parameter
For your case it might suffice to have a run method:
class GameRunner {
public static void mainEntry(MyGameInterface mgi) {
}
}
And the implementors may do
cöass ThirdPartyGame implements MyGameInterface {
}
GameRunner.mainEntry(new ThirdPartyGame());
Plugin with java reflection
You can make your ad-hoc, self-define plugin emchanism, and use java reflection to instantiate the class. The third party jar must be placed at some location, that is in the class path, as defined in your jar's manifest. The class somewhere defined:
String klazz = resBundle.getProperty("pluginClass");
Class<MyGameInterface> klazz = Cass<MyGameInterface>.forName(klazz);
MyGameInterface game = klazz.getConstructor().newInstance();
If I understood your question correctly it seems you have slightly misunderstood polymorphism, you don't need to know the type that implements the interface.
See the following example, there is only one class that directly knows the types of each enemy, the initializing class.
import java.util.ArrayList;
import java.util.List;
public class SO18671999 {
public static interface Enemy {
public void Attack(Enemy other);
public String getName();
}
public static class Dragon implements Enemy {
String name = "Onyxia";
public void Attack(Enemy other) {
System.out.println(this.name + " attacks " + other.getName()
+ " for 10 dmg!");
}
public String getName() {
return this.name;
}
}
public static class Cerberus implements Enemy {
private String name;
private int dmg;
public Cerberus(String name, int dmg) {
this.name = name;
this.dmg = dmg;
}
#Override
public void Attack(Enemy other) {
System.out.println(this.name + " attacks " + other.getName()
+ " for " + this.dmg + " dmg!");
}
#Override
public String getName() {
return this.name;
}
}
public static class EnemyInitializer {
private List<Enemy> enemies;
public EnemyInitializer() {
enemies = new ArrayList<>();
enemies.add(new Dragon());
enemies.add(new Cerberus("CerberusHeadLeft", 10));
enemies.add(new Cerberus("CerberusHeadRight", 10));
enemies.add(new Cerberus("CerberusHeadCenter", 20));
}
public List<Enemy> getEnemies() {
return enemies;
}
}
public static class EnemyAttacker {
private EnemyInitializer eI = new EnemyInitializer();
public void startAttacking() {
List<Enemy> enemies = eI.getEnemies();
for (Enemy one : enemies) {
for (Enemy two : enemies) {
if (one == two)
continue;
one.Attack(two);
}
}
}
}
public static void main(String[] args) {
EnemyAttacker eAttacker = new EnemyAttacker();
eAttacker.startAttacking();
}
}
Why won't this class compile?
class Exam {
private int score;
// constructor initializes score to 99
public void Exam() {
score = 99;
}
// returns the current value of score
private int getScore() {
return score;
}
// returns the String representation of the Object
public String toString() {
return "The score is " + getScore();
}
}
Your constructor shouldn't have a return type. Not even void.
public Exam() {
score = 99;
}
A construct should not contain the void keyword:
public Exam() {
score = 99;
}
A constructor returns a reference the the newly created object. But you don't have to write it. So thinking it is void is wrong as well.
Constructors don't need return types. Remove void and you should be set.
In a constructor you don't use void.
Write the constructor as:
public Exam() {
score = 99;
}
The main problem is the missing package declaration.
package yourpkg;
class Exam {
Additionally, the return type on the for Exam() makes it a function instead of a constructor and will result in a warning.
Just a suggestion not related to the concrete problem:
private int score;
// returns the current value of score
private int getScore() {
return score;
}
There is no point in having that getScore() if your going to keep it private. Make it public.
Also, always use the #Override annotation whenever your intention is to override some method. Compiler will let you known in case you are failing to do so. That means bug prevention.
e.g.
// returns the String representation of the Object
#Override
public String toString() {
return "The score is " + getScore();
}