I have three classes
public abstract class Champion
{
private String name;
public Champion(String ChName)
{
name = ChName;
}
public void setName(String ChName)
{
name = ChName;
}
public String getName()
{
return name;
}
}
second:
public class Mage extends Champion {
public Mage(String ChName)
{
super(ChName);
}
public String toString()
{
return String.format("%s",super.toString());
}
}
and my main:
public class JavaApplication2 {
public static void main(String[] args) {
Mage mage = new Mage("ori");
System.out.println("champion is "+mage);
}
}
The output should be "champion is ori"
but I get:
"champion is javaapplication2.Mage#1fee6fc"
What am I doing wrong?
You need to override toString() in Champion as the call to super.toString() in Mage.toString() will be calling Object.toString().
By calling super.toString() you call the Object toString() method, giving you the result you see.
You need to implement the Champion toString() method.
Related
What I should change to print the name of chair, which is chairNumber1?
public class Employee {
private Chair s;
Employee(Chair s) {
this.s = s;
}
void showData() {
System.out.println("Name of chair : " + s);
}
}
public class Chair {
}
public class Hlavna {
public static void main(String[] args) {
Chair s = new Chair("chairNumber1");
Employee c1 = new Employee(s);
c1.showData();
}
}
Why when I want to print name of the Chair, which is chairNumber1, Java prints on console the address of chairNumber1, but not it's name?
You must be already aware of the fact that every class in Java inherits a class called Object by default. This class has a method toString() which returns a string consisting of the name of the class of which the object is an instance, the at-sign character `#', and the unsigned hexadecimal representation of the hash code of the object.
When you use System.out.println("Name of chair : " + s);, it will call s.toString() but since you haven't provided your own implementation of toString() inside class Chair, it will call the toString() method of class Object which is the default superclass of class Chair. This is why you see the value which you think as the address of chairNumber1.
To get your desired String, you need to override the toString() method something like:
public class Chair {
private String name;
public Chair(String name) {
this.name = name;
}
public String toString() {
return name;
}
}
define a method inside your chair class that returns the name or override the toString method.
example:
public class Chair{
private String chairName;
Chair(String chairName){
this.chairName = chairName;
}
public String toString(){
return chairName;
}
}
now inside showdata() call toString():
void showData(){
System.out.println("Name of chair : " + s.toString());
}
There are a couple of things going on here.
You have created a chair object in your main method of your Hlavna class. To this Chair object you have provided an argument, although from the code above Chair does not take an argument.
In the same way that you have made the Employee class take an argument of chair, you should take the Chair take an argument of name, like so:
public class Chair
{
private String name;
Chair(String chairName)
{
this.name = chairName;
}
}
Now this isn't enough. When you print any Java object, under the hood what is really happening is the object's toString method is called. By default this prints the object's address, but you can override that by implementing the method yourself, like so:
public class Chair
{
private String name;
Chair(String chairName)
{
this.name = chairName;
}
public String toString()
{
return this.name;
}
}
Now, when you print a chair object it will call the Chair object's implementation of toString, which here returns the chair's name.
Your employee class is correctly printing the "toString()" method of the chair that you pass to it as you construct it, but currently that looks like an address. If you change the Chair object to the above code, that will instead print the chair name, which is what you are after.
The full code would look like this:
public class Employee
{
private Chair s;
Employee(Chair s)
{
this.s = s;
}
void showData()
{
System.out.println("Name of chair : " + s);
}
}
public class Chair
{
private String name;
Chair(String chairName)
{
this.name = chairName;
}
public String toString()
{
return this.name;
}
}
public class Hlavna
{
public static void main(String[] args)
{
Chair s = new Chair("chairNumber1");
Employee c1 = new Employee(s);
c1.showData();
}
}
public class Chair {
private String name;
public Chair(String name) {
this.name = name;
}
#Override
String toString() {
return name;
}
}
This is for learning. I have an interface that is implemented by 2 classes, and I am supposed to reduce the amount of code I use in order to keep things more clean and less messy. Currently, the code looks like this:
public abstract class VClass implements IntFace {
protected String name;
public VClass(String name) {
this.name = name;
}
public int value (SClass sc) {//comes from a diff class
return sc.lookup(name);
}
public String getName() {
return name;
}
#Override
public String toString() {
return getName();
}
}
public abstract class NClass extends VClass implements IntFace {
public Number(String name) {
super(name);
this.name = name;
}
public int value (SClass sc) {
return sc.lookup(name);
}
public String getName() {
return name;
}
#Override
public String toString() {
return getName();
}
}
public interface IntFace {
public int value (SClass sc);
public String toString (int num);
}
can this code be more condensed?
You can remove the following things from your code:
implements IntFace from NClass declaration. Since NClass extends VClass, it implements IntFace as well.
this.name = name; from NClass constructor. name is initialized in a superclass constructor
value and getName methods from NClass. These methods are implemented in a superclass.
public modifier from interface methods declaration. Methods in interfaces are public by default.
Now you can also make name field private since it's no longer used in a NClass.
I have a question about this code:
public class Musician {
private String name;
public String instrument;
public Musician(String name, String instrument){
this.name= name;
this.instrument= instrument;
}
public String getInstrument() {
return instrument;
}
public String getName() {
return name;
}
private String getClassName(){
return "Musician ";
}
public void play(){
System.out.println("[M] "+getClassName() + " plays music.");
}
public void printInfo(){
play();
System.out.println("[M] Class name: "+ getClassName());
System.out.println("[M] Instrument: "+ getInstrument());
}
}
public class RockMusician extends Musician{
public String instrument;
public RockMusician(String name, String instrument) {
super(name, instrument);
this.instrument= instrument + " and drums";
}
public String getClassName(){
return " RockMusician ";
}
public void play(){
System.out.println("[RM] "+ getClassName() + getName() + " breaks his "+ super.getInstrument() + "!");
}
}
public class IsraelyRockMusician extends RockMusician {
public IsraelyRockMusician(String name, String instrument) {
super(name, instrument);
}
public String getInstrument() {
return instrument;
}
public String getName(){
return super.getName() + " the king";
}
public String getClassName() {
return " IsraelyRockMusician ";
}
}
public class Testing {
public static void func(Musician m){
System.out.println("I've got a musician!");
}
public static void func(RockMusician m){
System.out.println("I've got a rock musician!");
}
public static void main(String[] args) {
Musician m3 = new IsraelyRockMusician("Chanoch", "guitar");
m3.printInfo();
}
}
I have IsraeliRockMusician who inherits RockMusician who Inherits Musician,
I then make a Musician m3 with the name "chanoch" and instrument "guitar"
and I active the method, print Info,
because the printInfo is in the father -> RockMusician which contains 3 methods on itself-> play(),getClassName(),and getInstrument(),
my question is, when the method showinfo runs, play is going all the way to the overwriten method and prints "[RM] IsraelyRockMusician Chanoch the king breaks his guitar!",
now this is fine, but the next line is "[M] Class name: Musician ", which means the getClassName was given "Musician" and Im asking why its not "IsraeliRockMusician" since the method was overwritten.
I'm sorry if the question is a bit hazey.
The problem is that the method of the base class has private access.
private String getClassName(){
return "Musician ";
}
Change it to public/protected so you can override it.
Instead of having a function where you hardcode the class name, you should use the following:
public class Foo {
public void printClassName() {
System.out.println(this.getClass().getName());
}
}
This way, if you change your class name, you don't need to update the method that you've written. One caveat to this is if you run an obfuscation tool against your code, the class name may be replaced with random characters. In that case, you can create a const string in your class and refer to that instead.
For my assignment, I am trying to throw an exception so that my program does not allow objects "Wolf" to eat "Plants". I am however struggling to find a way to implement this. I have so far tried using an if statement to search for the condition of food (x) being equal to "Plants" but this does not seem to be working. Here is the code:
Animal class
abstract public class Animal
{
String name;
int age;
String noise;
abstract public void makeNoise();
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
abstract public Food eat(Food x) throws Exception;
}
Food class
public class Food {
//field that stores the name of the food
public String name;
//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}
public String getName() {
return name;
}
}
Carnivore class
public class Carnivore extends Animal
{//if statement that throws exception
public Food eat(Food x) throws Exception
{
if (x.equals(new Meat("Plants"))) {
throw new Exception("Carnivores only eat meat!");
} else {
return x;
}
}
public void makeNoise()
{
noise = null;
}
public String getNoise()
{
return noise;
}
}
Meat class
public class Meat extends Food
{
public Meat(String name) {
super(name);
}
public String getName() {
return super.getName();
}
}
Wolf class
public class Wolf extends Carnivore
{
Wolf()
{
name = "Alex";
age = 4;
}
public void makeNoise()
{
noise = "Woof!";
}
public String getNoise()
{
return noise;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public String eat(String x)
{
return x;
}
}
Main
public class Main {
public static void main(String[] args)
{
Wolf wolfExample = new Wolf();
System.out.println("************Wolf\"************");
System.out.println("Name = " + wolfExample.getName());
System.out.println("Age = " + wolfExample.getAge());
wolfExample.makeNoise();
System.out.println("Noise = " + wolfExample.getNoise());
Meat meatExample = new Meat("Plants");
System.out.println("************Wolf eating habits************");
System.out.println("Wolves eat " + wolfExample.eat(meatExample.getName()));
}
}
Output
************Wolf"************
Name = Alex
Age = 4
Noise = Woof!
************Wolf eating habits************
Wolves eat Plants//this should throw exception message
Any help on how to fix this to get the desired output would be greatly appreciated, thanks.
This code is causing the problem:
if (x.equals(new Meat("Plants"))) {
throw new Exception("Carnivores only eat meat!");
} else {
return x;
}
You don't have a equals method defined in your classes, so it compares objects using == operator - checking if the references are the same.
This expression:
x == (new Meat("Plants"))
is always false - new operator creates new instance of Meat object so the reference is always different.
Do not use equals to check types, use instanceof operator instead.
So your code should look like this:
public Food eat(Food x) throws Exception
{
if (x instanceof Meat) {
return x;
} else {
throw new Exception("Carnivores only eat meat!");
}
}
In that case you will need to define Plant class that extends Food.
Alternatively you can define equals method in your Food class that compares name field.
How to override equals method in java
I am writing a program that is based on the demonstration of inheritance. I am trying to write an exception so that the only parameter that can be passed into the Meat class which is linked to the class Wolf. In essence, I am trying to allow the only parameter that can be passed into the eating method to be a Food variable called Meat. Here is the code:
Animal
abstract public class Animal
{
String name;
int age;
String noise;
abstract public void makeNoise();
public String getName() {
return name;
}
public void setName(String newName) {
name = newName;
}
abstract public Food eat(Food x) throws Exception;
}
Food
public class Food {
//field that stores the name of the food
public Food name;
//constructor that takes the name of the food as an argument
public Food(Food name){
this.name = name;
}
public Food getName() {
return name;
}
}
Meat
public class Meat extends Food
{
public Meat(Food name)
{
super(name);
}
public Food getName()
{
return super.getName();
}
}
Carnivore
public class Wolf extends Carnivore
{
Wolf()
{
name = "Alex";
age = 4;
}
public void makeNoise()
{
noise = "Woof!";
}
public String getNoise()
{
return noise;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public Food eat(Food x) throws Exception
{
if (x instanceof Meat) {
return x;
} else {
throw new Exception("Carnivores only eat meat!");
}
}
}
Wolf
public class Wolf extends Carnivore
{
Wolf()
{
name = "Alex";
age = 4;
}
public void makeNoise()
{
noise = "Woof!";
}
public String getNoise()
{
return noise;
}
public String getName()
{
return name;
}
public int getAge()
{
return age;
}
public Food eat(Food x) throws Exception
{
if (x instanceof Meat) {
return x;
} else {
throw new Exception("Carnivores only eat meat!");
}
}
}
Main
public class Main {
public static void main(String[] args)
{
Wolf wolfExample = new Wolf();
System.out.println("************Wolf\"************");
System.out.println("Name = " + wolfExample.getName());
System.out.println("Age = " + wolfExample.getAge());
wolfExample.makeNoise();
System.out.println("Noise = " + wolfExample.getNoise());
Meat meatExample = new Meat(//Food argument goes here?);
System.out.println("************Wolf eating habits************");
System.out.println("Wolves eat " + wolfExample.eat(meatExample.getName()));
}
}
The problem I'm having is that I cannot pass in anything as a food argument within the new Meat object that I create within my main method. And I mm getting the error of an unsupported exception when I try to call System.out.println("Wolves eat " + wolfExample.eat(meatExample.getName()));which I think may be because a Food variable has not been passed in. The desired outcome is that a Food variable such as Plants is passed in which throws an exception message. Any help on how to resolve this is appreciated, thanks.
You will have to modify your Animal and Food classes first and then with few other changes in your Main class, you may be able to achieve what you are trying to. Here are few suggested changes:
public class Food {
//field that stores the name of the food
public String name;
//constructor that takes the name of the food as an argument
public Food(String name){
this.name = name;
}
public String getName() {
return name;
}
}
public class Meat extends Food
{
public Meat(String name) {
super(name);
}
public String getName() {
return super.getName();
}
}
public class Main {
public Main() {
super();
}
public static void main(String[] args) {
Wolf wolfExample = new Wolf();
System.out.println("************Wolf\"************");
System.out.println("Name = " + wolfExample.getName());
System.out.println("Age = " + wolfExample.getAge());
wolfExample.makeNoise();
System.out.println("Noise = " + wolfExample.getNoise());
try {
Meat meatExample = new Meat("Steak");
//Food vegFood = new Food("Spinach");
System.out.println("************Wolf eating habits************");
wolfExample.eat(meatExample);
//wolfExample.eat(vegFood);
} catch (Exception e) {
// TODO: Add catch code
e.printStackTrace();
}
}
}
So, If you call wolfExample.eat(vegFood); your code will throw exception.
First of all, your Carnivore class and Wolf class is same.
You have not passed name for your 'meatExample'
And try instantiating Meat object and assign it in Food class
Food meatExample = new Meat("Beef");
This way you are calling getName() method of Food class rather than from Meat class.
Basically, your Food and Meat class design is incorrect, which needs to be fixed as shown below i.e., Meat class should take the argument of food name property.
Food class:
public abstract class Food {
//field that stores the name of the food
protected String name;
public String getName() {
return this.name;
}
}
Meat class:
public class Meat extends Food {
public Meat(String name) {
super.name = name;
}
//other methods or add other specific meat fields
}
main() method:
public static void main(String[] args) {
//Create the Meat Object by sending the name in constructor
Meat meatExample = new Meat("Chicken");
//other code
}