Java Static constructor not working - java

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)

Related

Super class is not passing along values

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

I am trying to implement OOP concepts with java

When i try to compile an aggregation program , i receive an error saying "class,interface,enum expected". Here is my code. please help me solve this issue.
class employee
{
private String name;
private String address;
private float salary;
public employee(String na, String add,float sal)
{
name = na;
address = add;
salary = sal;
}
public void showEmpDetails()
{
System.out.println("Name " + name);
System.out.println("Address " + address);
System.out.println("Salary " + salary );
System.out.println();
}
}
import java.util.vector;
class company
{
private String comname;
private vector vt;
public company(String na)
{
comname = na;
vt = new vector();
}
public void addEmployee(employee e)
{
vt.addElement(e);
}
public void showComDetails()
{
System.out.println("Company Name " + comname);
int x = vt.size();
int y = 0;
while(y<x)
{
object e = vt.elementAt(y);
e.showEmpDetails();
y++;
}
}
}
public class demo
{
public static void main(String[] args)
{
employee e1 = new employee("Ashan","Kandy",2000.0f);
employee e2 = new employee("Steve","California",2500.0f);
employee e3 = new employee("Elon","South Africa",2500.0f);
company c1 = new company("Apple");
c1.addEmployee(e1);
c1.addEmployee(e2);
c1.addEmployee(e3);
c1.showComDetails();
}
}
Note:- i receive only one error. and also can anybody tell me why can't i have more than one public class in java.
Well, your code has more than one error actually. The reason for your specific error is that import should be at beginning of the file, not in the middle.
And my understanding of why only one public class is allowed for each file is:
It makes things clearer.
By reading the class name and document to this class, you could quickly know what the whole file is used for. If we allow multiple public classes in one file, like C++, then we have to jump inside of the file to understand it.
Notice Java is a strong object-oriented language, i.e. everything in Java is Object. So when importing, you are importing a file. It would be more complicated if one file contains multiple public classes.
It simplify testing.
Each public class could have a main function. And you could run any main function of a file Demo.java simply by java Demo. This is really nice, so that you could write test code, or example of usage in main function to show other contributor how this class should be used.
There have to be other more in-depth reason for single public class in Java. But these are my perspective.

How to access class field variable inside all methods from toString twin toStrung?

Once upon modifying the above with static modifiers, line 16 requires the following syntax:
getLegs();toStrung();
//I think this is essentially printing the last called method updating class field variable toString. For example, to do setLegs();toStrung(); prints setLegs()'s toString.
Question: How should one access a shared field within methods? What if I included it into the constructor? Ideally, I want the code to look like getLegs().toStrung() and for toString to be a clean slate for every method.
My answer: I think a seperate instance of String toString inside each method works to get a clean slate appeal, but the syntax doesn't make sense. I know it is about my design. I think a solution would be a new class, but this returns to the same conflict that relates to the class field variable.
public class Dog{
public String toString;
public Dog(String name){
this.name = name;
}
public int getLegs(){
toString = "Dog has " + legs + " legs.";
return legs;
}
public int setLegs(int legs){
toString = getName() + "'s legs have changed from "
+ getLegs() + " to " + legs + ".";
this.legs = legs;
return this.legs;
}
public void toStrung(){
System.out.println(Dog.toString);
}
public static void main(String[] args){
Dog Dundt = new Dog("Dundt");
Dundt.getLegs();
Dundt.toStrung();
}
1) toString() should not be a static member.
2) getLegs() should not have the side effect of changing the member String toString.
3) There should not be a member variable String toString.
4) toString() should return a String.
5) name needs to be a member.
6) legs needs to be a member.
7) toString() should generate the string from the members at run time.
8) You do not need to explicitly call toString() in main. Simply passing the instance of Dog to println will call it for you.
9) It is good practice to annotate methods you are overriding with the #Override annotation. toString() is a member of Object and you are overriding Object.
public class Dog{
private String name;
private int legs = 4;
public Dog(String name){
this.name = name;
}
public int getLegs(){
return legs;
}
public int setLegs(int legs){
this.legs = legs;
return this.legs;
}
#Override
public String toString(){
return "Dog is called " + name + " it has " + legs + " legs.";
}
public static void main(String[] args){
Dog dundt = new Dog("Dundt");
System.out.println(dundt);
}
}

How to print a String defined in one class in a different class?

I have two classes. In the first one, I used the Scanner to retrieve the user's name and then store it in a String called name. Then say, I start a new class, and want to print that came out, how do I go about it. So I just wrote up this code as an example, so you can get an idea of what I'm trying to ask. I'll post both classes.
import java.util.Scanner;
public class One {
public static void main(String[] args) {
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two object = new Two();
}
}
}
Second class.
public class Two {
public Two() {
System.out.println("Ok "+One.name+", lets start!");
}
}
So, you will probably be doing something like this: -
class One
{
private String name = "bob";
public String getName()
{
return name;
}
public static void main(String [] args)
{
One one = new One();
Two two = new Two(one);
// You could also just pass an r-value to Two, as in, Two(new One()) if you
// never require 'one' again
}
}
class Two
{
public Two(One one)
{
System.out.println("Ok " + one.getName() + ", lets start!");
}
}
What is going on?
Creating two classes in your main entry point method.
Passing the instance of One to the constructor of Two
Two then calls getName()
You could, as others have suggested, pass a string as the constructor; alternatively, you could do both if required as Java supports overloading methods see
Recommendations
Take a look at http://docs.oracle.com/javase/tutorial/java/javaOO/methods.html for overriding methods so that you may see how to pass both a string and an object reference by value. What you are doing right now is passing the object reference of one by value. It may not be needed or you may want to provide restrictions using an interface, see http://docs.oracle.com/javase/tutorial/java/concepts/interface.html
Use the constructor to pass the values
public class Two {
private String value;
public Two(String a){
this.value=a;
System.out.println("Ok "+value+", lets start!");
}
//getter and setters
}
Then while creating the instance use that constructor
Two object = new Two(name);
pass your value to the Two class constructor.
if(start != null){
Two object = new Two(start );
}
and
public Two(String s){
System.out.println("Ok "+s+", lets start!");
}
To make your code compile, move the String name variable into a static field:
public class One {
public static String name;
public static void main(String[] args){
// Note: The "name" variable is no longer defined here
String start; // etc
// rest of code the same
}
}
I'm not going to tell you this is good code design, but it does what you asked.
You will also do like this
public class One {
private String name;
public void setName(String name){
this.name = name;
}
public String getName(){
retrun this.name;
}
public static void main(String[] args){
String name;
String start;
Scanner input = new Scanner(System.in);
System.out.println("Hello, what is your name?");
name = input.nextLine();
System.out.println("Hello "+name+", welcome! To ocntinue, please hit any key.");
start = input.nextLine();
if(start != null){
Two two = new Two();
two.printName(this);
}
}
class Two{
public void printName(One one){
System.out.println("" + one.getName() );
}
}

How can I avoid getters AND avoid hard coding the UI?

I want to print a description of a warrior to the console that will include the warrior's strength and the warrior's weapon in the form This <description> warrior uses a <weapon> For example: This strong warrior uses a butter knife.
Edit for clarity: I want to do this without asking objects for data by using getters or any other method (like toString) which reveals the internal implementation of an object. I also want to do this without hard coding my current UI (a console) into the objects themselves.
public class Warrior
{
private String description;
private Weapon weapon;
public Room(String description, Weapon weapon)
{
this.description = description;
this.weapon = weapon
}
}
public class Weapon
{
private String name;
public Weapon(String name)
{
this.name = name;
}
}
Avoiding Getters
I can avoid getters by hard coding the UI:
//Warrior class
public void display()
{
String.out.println("This " + description + " warrior uses a ");
weapon.display();
}
//Weapon class
public void display()
{
String.out.print(name);
}
Avoiding hard coded UI
I can avoid a hard coded UI by using getters:
//Warrior class
public String getDescription()
{
return "This " + description + " warrior uses a " + weapon.getName();
}
//Weapon class
public String getName()
{
return name;
}
Is it possible to avoid both? How can I do so in the above example?
Note: In response to some initial answers, a getter is not a method that follows the naming convention getSomeFieldName. Therefore, renaming getSomeFieldName to aMethodThatIsNotPrefixedByGet is not a solution. A getter is a method that passes private data from an object to the scope which called it.
To be completely clear, the issue I am trying to deal with here is to do with data encapsulation (as this question is tagged). How can I prevent passing data to objects which do not need to know that data and still avoid hard coding the UI?
Additionally, based on these questions, I don't think toString should be used in the way that it has been suggested by the many of the answers. toString seems to be for generating a text representation of an object for debugging and so forth, not for returning arbitrary output and especially not for returning application dependent output.
Yes go for i18n,
messages.properties
displayMessage = This {0} warrior uses a {1}
messages.properties_en_US
displayMessage = This {0} warrior uses a {1}
and
public static String getString(String key, Object... params ) {
try {
return MessageFormat.format(RESOURCE_BUNDLE.getString(key), params);
} catch (MissingResourceException e) {
return '!' + key + '!';
}
}
I would override the method toString() in both the Warrior and the Weapon, as this method naturally returns a String represenation of an object. Then I would create a class dedicated to creating the descriptions, for example a DescriptionMaker, and create a method in it:
String createDescription(Warrior warrior, Weapon weapon)
{
return "This " + warrior + " uses a " + weapon;
}
The return value of this method could then be printed to the console. Also, internalization could be applied in the DescriptionMaker class.
In that case getters seem a good practice to me as they permit you to have your data (Warrior and Weapon classes) separate from your UI (that calls the getters and create the description strings, widgets, html code, etc.). However I wouldn't let the Warrior getter create the string, it would just return the warrior description and the UI class would create the string (what the Warrior.getDescription() method you propose do in you sample).
YOu can override toString in your Warrior class to achieve it.
public String toString() {
return "This " + this.description + " warrior uses a " + weapon.toString();
}
override toString inWeapon to return the name;
as
public String toString() {
return this.name;
}
and you can directly print as
System.out.println(warrior);
public Interface IWarriorView {
public void display(String description, Weapon weapon);
}
public Interface IWeaponView {
public void display(String name);
}
public class WeaponViewImpl {
public void display(String name) {
System.out.println(name);
}
}
public class WarriorViewImpl {
public void display(String description, Weapon weapon) {
System.out.println("This " + description + " warrior uses a ");
weapon.display(new WeaponImpl());
}
}
// Warrior class
public String display(IWarriorView view) {
view.display(description, weapon);
}
// Weapon class
public String display(IWeaponView view) {
view.display(name);
}
How about combining both:
//Warrior class
public String display()
{
return "This " + description + " warrior uses a "+weapon.display();;
}
//Weapon class
public String display()
{
return name;
}

Categories

Resources