Unable to print from toString() Java - java

I used toString() to call animal but it didn't identify the animal variable, the following is my code.
package animals;
public class Animal {
public String country;
public String commonNam;
public Animal(String name, String country){
Animal animal = new Animal("Emu", "Australia");
}
public String toString(){
Animal animal = new Animal("Emu", "Australia");
return String.format("%d,%d",animal);
}
public static void main(String[] args) {
System.out.println("Animal Test");
System.out.println(animal);
}
}
The result I want is as follow:
Animal Test
Emu, Australia

The code you gave above doesn't make much sense. Below is the corrected code. It will give you the result you want.
public class Animal {
public String country;
public String commonName;
public Animal(String name, String country) {
this.country = country;
commonName = name;
}
public String toString() {
return String.format("%s,%s",commonName,country);
}
public static void main(String[] args) {
Animal animal = new Animal("Emu", "Australia");
System.out.println("Animal Test");
System.out.println(animal);
}
}
Output:
Animal Test
Emu,Australia

To get your desired result you have to pass an object of Animal class not the Animal class it self
try :
System.out.println(new Animal("Emu", "Australia"));
instead of
System.out.println(Animal);
Your contructor method should be:
public Animal(String name, String country){
this.commonNam=name;
this.country=country;
}
And toString method:
public String toString(){
return String.format("%s,%s",this.animal,this.country);
}

Just replace System.out.println(Animal); with some object of Animal i.e. :
System.out.println(new Animal("Emu", "Australia");
You will get stack overflow exception because you are creating a new instance in cunstructor.
It is because cunstructor is creating a new instance recursively and infinitely.
To get rid of that replace your code in constructor with this one.
public Animal(String name, String country) {
this.commonNam = name;
this.country = country;
}

Related

Write a Dog constructor that has one argument, the name, and calls the super constructor passing it the name and the animal type “dog”. cant pass type

public class Pet
{
private String name;
private String type;
public Pet(String n, String t)
{
name = n;
type = t;
}
public String getType(){
return type;
}
public String getName(){
return name;
}
public void speak()
{
System.out.println("grr!");
}
public static void main(String[] args)
{
Pet p = new Pet("Sammy","hamster");
System.out.println(p.getType());
p.speak();
Dog d = new Dog("Fido");
System.out.println(d.getType());
d.speak();
//Cat c = new Cat("Fluffy");
//System.out.println(c.getType());
//c.speak();
}
}
class Dog extends Pet
{
public Dog(String name){
super(name);
}
public void speak(){
System.out.println("Woof");
}
}
// Add a Cat class
How do I add "type" to this without adding another String to my parameter?
I've tried other ways that obviously didn't work but I still tried anyway. So how do I add another object to my super class from Pet without adding more to my parameter?
Constructor with one parameter for the dog class:
public Dog(String name) {
super(name, "dog");
}

How to make array of inherited objects - Java

I have abstract class Animal and inheritance classes Fish and Dog.
I need to create various objects of fish and dogs and give them names and breeds and also make methods of the way they move.
Finally i need to create an array of them and do 4 random prints that will show their name and breed.
Main Class:
public class JavaApplication38 {
public static void main(String[] args) {
Animal[] arr = new Animal[20];
arr[0] = new Fish("Riby", "Sea Fish");
arr[1] = new Dog("Any", "Great Dane");
arr[2] = new Fish("Ribytsa", "River fish");
arr[3] = new Dog("Jackie", "Pug");
arr[4] = new Fish("Bobi", "Mix");
arr[5] = new Dog("Ruby", "Labrador");
}
}
Animal class
public abstract class Animal {
public Animal(String name, String breed){
}
public Animal(){
}
public abstract void moving();
}
Dog class
Public class Dog extends Animal{
private String breed;
private String name;
public Dog(){
}
public Pas(String name, String breed){
this.name = name;
this.breed =breed;
}
#Override
public void moving() {
System.out.print("Walk\n");
}
}
Fish class
public class Fish extends Animal {
private String breed;
private String name;
public Fish(){
}
public Fish(String name, String breed){
this.name = name;
this.breed= breed;
}
#Override
public void moving(){
System.out.print("Swims\n");
}
}
The question is, what do i have to write in a loop to print names and breeds via array?
The problem was that you defined name and breed separately in each subclass of Animal. You need to make name and breed instance variables in Animal. That way, Java knows that every single Animal has a name and breed.
public abstract class Animal {
private String name;
private String breed;
public Animal(String name, String breed) {
this.name = name;
this.breed = breed;
}
public getName() { return name; }
public getBreed() { return breed; }
public abstract void moving();
}
public class Dog extends Animal {
public Dog(String name, String breed) {
super(name, breed);
}
#Override
public void moving(){
System.out.print("Walks\n");
}
}
public class Fish extends Animal {
public Fish(String name, String breed) {
super(name, breed);
}
#Override
public void moving(){
System.out.print("Swims\n");
}
}
Now you can print the name and breed for any Animal, whether it's a Dog or Fish.
Animal[] arr = new Animal[6];
arr[0] = new Fish("Riby", "Sea Fish");
arr[1] = new Dog("Any", "Great Dane");
arr[2] = new Fish("Ribytsa", "River fish");
arr[3] = new Dog("Jackie", "Pug");
arr[4] = new Fish("Bobi", "Mix");
arr[5] = new Dog("Ruby", "Labrador");
for (Animal a : arr) {
System.out.println(a.getName() + " " + a.getBreed());
a.moving();
}

JAVA: How can I access to members of each classes?

How can I access to members of each classes?
I have class Dog and Cat. They have different member variable of class.
I try to create one function "CommUtil.display()" to access many classes (Dog or Cat) and display all members of class.
I try to access from mainClass to access Dog or Cat class.
but it can't.
Anyone can help will be appreciated.
I have made an example below:
class Dog {
private String name = null;
private String weight = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getWeight() {
return weight;
}
public void setWeight(String weight) {
this.weight = weight;
}
}
class Cat {
private String name = null;
private String age = null;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
}
class commUtil {
//TODO: output members of class
public void display (Object obj){
//Question: How to access members of each classes?
//code here...
}
}
class mainClass {
public static void main(String[] args) {
Dog d = new Dog();
commUtil.display(d);
or
Cat c = new Cat();
commUtil.display(c);
}
}
In case 1:
Dog d = new Dog();
d.setName("Lion");
d.setWeight("2Kg");
commUtil.display(d);
It will display Name and Weight of Dog
In case 2:
Cat c = new Cat();
c.setName("MiMi");
c.setAge("1");
commUtil.display(c);
It will display Name and Age of Cat
If the code can still change, you may be able to use java interface. The idea is that both Dog and Cat implements a common interface for output display. In practice though, it will have the same result as modifying toString() like the other comments already covered. Anyway, here is an example:
public interface AnimalInfo {
public String getInfo();
}
and then both Dog and Cat classes can implements this interface.
class Dog implements AnimalInfo {
...
public String getInfo() {
return "name="+name+", weight="+weight;
}
class Cat implements AnimalInfo {
...
public String getInfo() {
return "name="+name+", age="+age;
}
and then inside commUtil the argument can use the interface type AnimalInfo
public void display (AnimalInfo animal){
System.out.println("It will display " +
animal.getInfo() + " of " + animal.getClass().getSimpleName());
}
This is what inheritance is for, so you would make an abstract super class possibly called Animal in this case and then Dog and Cat would extend that class as subclasses. Here is a fairly simple tutorial about inheritance.
public abstract class Animal {
/** Common name property for all animals */
private String name;
/** Common age property for all animals */
private int age;
public Animal(String name, int age) {
this.name = name;
this.age = age;
}
public void setName(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setAge(int age) {
this.age= age;
}
public int getAge() {
return age;
}
/**
* Abstract method that will need to be implemented
* by a concrete class that inherits from this abstract class
*/
public abstract String getInfo();
public abstract String speak();
public abstract String getType();
}
public class Dog extends Animal {
/*
Any Dog specific properties would also go in here
*/
private boolean isPedigree = false;
/** Class Constructor */
public Dog(String name, int age, boolean isPedigree) {
super(name, age);
this.isPedigree = isPedigree;
}
public boolean isPedigree() {
return isPedigree;
}
#Override
public String getInfo() {
return "I am a Dog named " + name + " and I am " + age + " years old.";
}
#Override
public String speak() {
return "WOOF";
}
#Override
public String getType() {
return Dog.class.getSimpleName();
}
}
public class Cat extends Animal() {
/*
Any Cat specific properties would also go in here
*/
/** Class Constructor */
public Cat(String name, int age) {
super(name, age);
}
#Override
public String getInfo() {
return "I am a " + getType() + named " + name + " and I am " + age + " years old.";
}
#Override
public String speak() {
return "meow";
}
#Override
public String getType() {
return Cat.class.getSimpleName();
}
}
public class MyMainClass {
public static void main(String[] args) {
/*
Just creating a random array to show that
any animal whether Dog or Cat can be placed into
this array as they inherit from Animal
*/
List<Animal> animals = new ArrayList<>();
animals.add(new Dog("James", 5, true));
animals.add(new Cat("Treacle", 2));
for (Animal animal : animals) {
display(animal);
if (animal instanceof Dog) {
boolean isPedigree = ((Dog) animal).isPedigree();
System.out.println("Q: Am I a Pedigree? A: " + String.valueOf(isPedigree));
}
}
}
private void display(Animal animal) {
System.out.println("I'm an animal of type " + animal.getType() + " and I can say " + animal.speak());
System.out.println(animal.getInfo());
}
}
Our output would be:
I'm an animal of type Dog and I can say WOOF
I am a Dog named James and I am 5 years old.
Q: Am I a Pedigree? A: true
I'm an animal of type Cat and I can say meow
I am a Cat named Treacle and I am 2 years old.
This answer shows simple inheritance and polymorphism. This of the backbone of OOP (Object Orientated Programming) and when learning Java will be the essential basics you will need to learn and understand.
In my example getInfo() could actually just be a method in Animal as there is nothing specific it is doing per subclass. You could also move display into the Animal abstract class if you which, I only placed it here for the example.
There is no need for any CommonUtils class or anything like that here, everything you want can be done by simply learning about inheritance.
What we are saying in this example is Cat and Dog are Animals they inherit all the characteristics of any Animal. What you can't do though is create a random Animal object like Animal animal = new Animal("Paul", 4);, the Animal has to be of some sort of type whether that is of type Dog, Cat or some other Subclass of Animal you create (i.e. Bird, Fish or even Human).
You can have the CommonUtil class as shown below. Also, make the display method static as you are trying to access it using class name.
class CommUtil {
//TODO: output members of class
public static void display (Object obj){
//Question: How to access members of each classes?
//code here...
if(obj instanceof Dog) {
System.out.println(((Dog) obj).getName());
System.out.println(((Dog) obj).getWeight());
}
}
}
But as mentioned in the comments you can just override toString() method inside every class and display objects for all those classes.
public String toString() {
return "Cat [name=" + name + ", age=" + age + "]";
}
You can use Java reflection to get all fields from object, below is the example, you can achieve this by T parameter method in utility class
public class ArrayMain {
int x=10; String name="anil";
public static void main(String[] args) throws IllegalArgumentException, IllegalAccessException {
ArrayMain m = new ArrayMain();
m1(m);
SomeOther o = new SomeOther();
m1(o);
}
public int getX() {
return x;
}
public String getName() {
return name;
}
static <T> void m1(T type) throws IllegalArgumentException, IllegalAccessException {
Field[] f=type.getClass().getDeclaredFields();
for(Field f1:f) {
System.out.println(f1.getName());
System.out.println(f1.get(type));
}
}
}
Check if the object is an instance of Cat or Dog using the instanceof operator. Then you must perform a cast to access the object’s getter methods.
if(obj instanceof Cat){
Cat cat = ((Cat) obj);
System.out.println(cat.getName());
}

Constructor Dog in class Dog cannot be applied to given types

Not sure what the issue is here but I am trying to get this program to compile and I can't. I need this to creates and makes the dog, labrador, and yorkie to all speak. The hint I am given is that something is missing in the constructor of a subclass, but I'm not seeing it. The error I keep getting is that "Constructor Dog in class Dog cannot be applied to given types". I am really new to Java so any help you could give me would be great. Thank you in advance!
package dogtest;
public class DogTest {
public static void main(String[] args) {
Dog dog = new Dog("Spike");
System.out.println(dog.getName() + " says " + dog.speak());
Labrador boop = new Labrador(name, color);
Yorkshire beep = new Yorkshire(name);
}}
package dogtest;
public class Dog {
protected String name;
public void Dog(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
public String speak()
{
return "Woof";
}}
package dogtest;
public class Labrador extends Dog{
private String color;
private static int breedWeight = 75;
public Labrador(String name, String color)
{
this.color = color;
}
public String speak()
{
return "WOOF";
}
public static int avgBreedWeight()
{
return breedWeight;
}}
package dogtest;
public class Yorkshire extends Dog {
public Yorkshire(String name)
{
super(name);
}
public String speak()
{
return "woof";
}}
As stated in comments, a constructor is similar to a method and it should have the same name as your class name Dog (you did this part right), but that they don't have a return type in their signature. So in order to have constructor with a String argument change the
public void Dog(String name) // this is only a method with the same name as the class
{
this.name = name;
}
into
public Dog(String name) // this is a real constructor since doesn't have a return type
{
this.name = name;
}
Before you change the above method into a constructor, the following error:
"Constructor Dog in class Dog cannot be applied to given types"
is happening because when you don't specify a constructor explicitly, a default no-arg constructor would be added by the compiler. Then compiler gives you that error because it couldn't find a constructor with a String argument.
I fixed the compile errors of the code
remove the void keyword of constrctor 'public void Dog(String name)'
add super constructor call to the Labrador contractor 'super(name)'
convert string to the name and color parameters in main method
Labrador boop = new Labrador("name", "color");
Yorkshire beep = new Yorkshire("name");
I did not add the packages and imports to the code
public class DogTest {
public static void main(String[] args) {
Dog dog = new Dog("Spike");
System.out.println(dog.getName() + " says " + dog.speak());
Labrador boop = new Labrador("name", "color");
Yorkshire beep = new Yorkshire("name");
}
}
class Dog {
protected String name;
public Dog(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String speak() {
return "Woof";
}
}
class Labrador extends Dog {
private String color;
private static int breedWeight = 75;
public Labrador(String name, String color) {
super(name);
this.color = color;
}
public String speak() {
return "WOOF";
}
public static int avgBreedWeight() {
return breedWeight;
}
}
class Yorkshire extends Dog {
public Yorkshire(String name) {
super(name);
}
public String speak() {
return "woof";
}
}

How to add properties to ArrayLists that include inheritance?

I'm doing an assignment on inheritance and I have so far created a superclass a subclass. Within these classes, there are methods that have been added to define information such as an animal's name or age. Now I have been asked to do the following:
Create a Demo class with a main method that creates an ArrayList of Animal objects. Fill the list with different animals, also with different names and ages.
I'm completely confused by this. If I try to create animals within my new ArrayList it tells me that the Animal class is abstract and cannot be instantiated. Here is the contents of the relevant classes:
Animal class (super class)
abstract public class Animal
{
int age;
String name;
String noise;
Animal(String name, int age)
{
this.age = age;
this.name = name;
}
Animal()
{
this("newborn", 0);
}
abstract public void makeNoise();
public String getName() {
return name;
}
public int getAge()
{
return age;
}
public void setName(String newName) {
name = newName;
}
abstract public Food eat(Food x) throws Exception;
abstract public void eat(Food food, int count) throws Exception;
}
Wolf class (sub class)
import java.util.ArrayList;
public class Wolf extends Carnivore
{
ArrayList<Food> foodGroup = new ArrayList<>();
String name;
int age;
Wolf(String name, int age)
{
this.name = name;
this.age = age;
}
Wolf()
{
super();
}
public void makeNoise()
{
noise = "Woof!";
}
public String getNoise()
{
return noise;
}
public Food eat(Food x) throws Exception
{
if (x instanceof Meat) {
return x;
} else {
throw new Exception("Carnivores only eat meat!");
}
}
public void eat(Food food, int count) {
while (count > 0) {
addFood(food);
count--;
}
}
public void addFood(Food inFood)
{
foodGroup.add(inFood);
}
}
Demo class
import java.util.ArrayList;
public class Demo {
public static void main(String[] args)
{
ArrayList<Animal> animalGroup = new ArrayList<>();
//Add new Animals with properties such as name and age?
Animal wolf1 = new Wolf();
addAnimal(new Wolf("lnb1g16", 6));
}
public static void addAnimal(Animal inAnimal)
{
animalGroup.add(inAnimal);
}
}
Apparently I'm suppose to create an array of Animals in the Demo class based off of these prior classes? I don't understand how this would be done and why I need to create a another main method either. Any help on how I would write the Demo class would be much appreciated as I'm confused by what I have been asked to do, thanks.
Demo class
public static void main(String[] args)
{
ArrayList<Animal> animalGroup = new ArrayList<>();
//Add new Animals with properties such as name and age?
Animal wolf1 = new Wolf();
animalGroup.add(new Wolf("sam", 5));
animalGroup.add(new Wolf("george", 5));
animalGroup.add(new Wolf("patrick", 7));
}

Categories