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.
Related
I want to print the object array as a string. here is my code.
I have followed instructions in this page but could not get it. https://www.java67.com/2014/03/how-to-print-array-in-java-example-tutorial.html
class Tiger extends Animal implements Comparable<Tiger>
{
#Override
public int compareTo(Tiger t)
{
return this.stripes-t.stripes;
}
int stripes;
Tiger(String color,String name,int stripes)
{
super(color,name);
this.stripes=stripes;
}
#Override
void move()
{
System.out.println("Tiger moving");
}
}
class Main1
{
public static void main(String[] args)
{
Tiger[] tigers={new Tiger("red","tiger_1",12),
new Tiger("red","tiger_2",8),
new Tiger("red","tiger_3",10)};
Arrays.sort(tigers);
System.out.println( Arrays.toString(tigers));
}
}
I have tried Arrays.toString. but the output is a quite like this : [Tiger#7d4991ad, Tiger#28d93b30, Tiger#1b6d3586]
Override the toString class inside the Tiger class. and whatever info you want to print of a tiger object just return the info as string. Then this string will be printed whenever you print a tiger class. For example the following implementation of toString will print the name property of a tiger object.
#Override
public String toString(){
return this.name:
}
You need to override toString() of Tiger to customize the default implementation. Something ike:
#Override
public String toString()
{
return "Tiger{name=" + name + ", color=" + color + ", stripes=" + stripes + "}";
}
assuming name and color are inherited from Animal.
First you should override toString() in class Tiger
Class Tiger{
....
..
#override
public String toString(){
return name+" "+ color;
}
}
then you can use tiger.toString
Override toString() in Tiger class
import java.util.*;
class Tiger implements Comparable<Tiger>
{
#Override
public int compareTo(Tiger t)
{
return this.stripes-t.stripes;
}
int stripes;
String color;
String name;
Tiger(String color,String name,int stripes)
{
this.color=color;
this.name=name;
this.stripes=stripes;
}
#Override
public String toString()
{
return color + " " + name + " " + stripes;
}
}
public class Main1
{
public static void main(String[] args)
{
Tiger[] tigers={new Tiger("red","tiger_1",12),
new Tiger("red","tiger_2",8),
new Tiger("red","tiger_3",10)};
Arrays.sort(tigers);
System.out.println( Arrays.toString(tigers));
}
}
Ouptput:-
[red tiger_2 8, red tiger_3 10, red tiger_1 12]
Im practicing polymorphism and inheritance, and i made a class (Animals) that sets the name of the animal, then i made a subclass (Cat) that sets the sound it makes, favourite toy.. all that. i tried testing it in a seperate class (Test) to print out "Cat likes to Moew, its favourite toy is Yarn" but its not working unless i extend Cat in the test class.
Heres my code.
Animals.java
public class Animals {
protected static String name;
public Animals() {
}
public Animals(String name) {
this.name = name;
}
public String setName(String newName) {
return this.name = newName;
}
public String getName() {
return name = name;
}
public static void animMove() {
System.out.println(name + " likes to walk");
}
}
Cat.java
public class Cat extends Animals {
public static String sound;
public static String favToy;
public String getSound(String sound) {
return this.sound = sound;
}
public String getToy(String favToy) {
return this.favToy = favToy;
}
public Cat() {
}
public Cat(String name, String sound, String favToy) {
super(name);
this.sound = sound;
this.favToy = favToy;
}
}
test.java
public class test{
public static void main(String[] args) {
Animals anim = new Animals();
Cat cat = new Cat("Cat", "moew", "Yarn ball");
System.out.println(anim.getName() + " Likes to " + cat.getSound(sound)
+ ", its favourite toy is a " + cat.getToy(favToy));
}
}
All works fine if i extend Cat to the test class, but when i dont, none of the variables like sound and favToy work. how would i do this without extending anything to the test class
Do not make the name variable static. This would mean that it belongs to the class and not an Animal object, meaning there will only ever be one Animal.name in the class. Your Cat.sound, Cat.favoriteToy variables are also static, which will mean all cats will have the same sound and same favorite toy (I guess this is acceptable, but then dont assign this in a constructor).
Setters don't need to have a return value (you are only changing some variable). For example:
public void setName(String newName) {
this.name = newName;
}
Getters do not need any parameters. You already know what to return, no need for a parameter. For example:
public String getSound() {
return this.sound;
}
Also, your Animals should be Animal, as this class represents a single animal.
If you create a Cat object, this will automatically be Animal as well (its inherited), so no need to create both, as you do in your main method
Cat myCat = new Cat("Purr","meow","ball"); //create cat
System.out.println(myCat.getName());
variables are static so all cats will have this name, sound and fav toy now...
Maybe you tried to do something like
1)
public class Animal {
protected String name;
public String animMove() {
return new String(this.name + " likes to walk");
}
}
2)
public class Cat extends Animal {
public String sound;
public String favToy;
public Cat(String name, String sound, String favToy) {
super(name);
this.sound = sound;
this.favToy = favToy;
}
public String getName() {
return super.name;
}
public String getSound() {
return this.sound;
}
public String getToy() {
return this.favToy;
}
}
3)
public class test{
public static void main(String[] args) {
Animal anim = new Cat("Cat", "moew", "Yarn ball");
System.out.println(anim.getName() + " Likes to " + anim.getSound(sound) + ", its favourite toy is a " + anim.getToy(favToy) + " " + anim.animMove());
}
}
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
}
To my understanding of the error, the most common cause is because I haven't included "public static void main (String[] args)", but I've done this prior to discovering the error, which is leaving me stumped. Can anyone help me out?
import java.io.*;
class basketBall
{
private String name;
private double number;
private String team;
// declare getter method public
public String getName()
{
return name;
}
// declare setter method public
public void setName(String n)
{
name = n;
}
// declare getter method public
public String getTeam()
{
return team;
}
// declare setter method public
public void setTeam(String t)
{
team = t;
}
// declare getter method public
public double getNumber()
{
return number;
}
// declare setter method public
public void setNumber(double num)
{
number = num;
}
// declare dribble method
void dribble()
{
System.out.println (name + ", " + number + " dribbles down the court...");
}
// declare shoot method
void shoot()
{
System.out.println (name + " shoots... And he scores, for the " + team + "'s!");
}
}
// test class for basketBall class
class basketBallTester
{
public static void main (String[] args)
{
//construct player and fills in its objects
basketBall Player1 = new basketBall();
// fill in objects of player1
Player1.setName("Ethan");
Player1.setTeam("Vikings");
Player1.setNumber(15);
// call methods
Player1.dribble();
Player1.shoot();
}
}
You have several options to run your program this. One of them is:
Create a separate basketBallTester.java file, and place there your class basketBallTester.
Compile both files: basketBallTester.java and basketBall.java
Run your program with java basketBallTester
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.