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();
}
Related
I am fairly new to coding please help me understand how to use inheritance in android with Java. Let me explain my question with an example :
Like there is a parent class called "Animal" which includes "name" and "age" and has two subclasses "Dog" and "Cat". The "Dog" class has "name", "age", "food" and the "Cat" class has "name", "age", "breed" as their attributes.
From my understanding the best practice is to make:
Animal class with the attribute of "name", "age" + constructor and getter and setter
public class Animal{
private String name;
private int age;
public Animal() {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
Dog class extends of Animal class with an attribute of "food" and put getter and setter
private String food;
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
}
Cat class extends of Animal class with an attribute of "breed" and put getter and setter
private String breed;
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
MainActivity should be like
public class MainActivity extends AppCompatActivity {
ArrayList<Animal> mAnimal = new ArrayList<>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Dog dog = new Dog();
dog.setName("The Dog");
dog.setAge(2);
dog.setFood("Bone");
Cat cat = new Cat();
cat.setName("The Cat");
cat.setAge(1);
cat.setBreed("Persian");
mAnimal.add(dog);
mAnimal.add(cat);
}
}
Now Since there are three classes and each class has a different attribute, How to implement listview to show a list of all animals and their foods or breeds (depends on which one they have) in Mainactivity?
I would really appreciate your answers in advance
Your question Refers to Inheritance but also to polymorphism.
create a super class and sub classes
class Animal {
protected String name;
protected int age;
public void animalSound() {
System.out.print("The animal makes a sound");
}
}
class Cat extends Animal {
private boolean isLivesAtHome;
//getters & setters
//override function from super class
public void animalSound() {
System.out.print("The Cat says meow");
}
}
class Dog extends Animal {
private boolean isWasVaccinatedAgainstRabies;
//getters & setters
//override function from super class
public void animalSound() {
System.out.print("The dog says bow wow");
}
}
run this on Main function like this:
class Main {
public static void main(String[] args) {
Animal myAnimal = new Animal(); // Create a Animal object - Super Class
Animal myCat = new Cat(); // Create a Cat object
Animal myDog = new Dog(); // Create a Dog object
ArrayList<Animal> arr = new ArrayList<>();
arr.add(myCat);
arr.add(myDog);
arr.add(myAnimal);
//simple for loop
for (int i = 0; i < arr.size(); i++){
//if the object is a Cat instance
if(arr.get(i) instanceof Cat){
//change Cat instance variable
((Cat)arr.get(i)).setLivesAtHome(true);
System.out.println("I'm a Cat");
}
//print animalSound function
arr.get(i).animalSound();
}
}
}
This code print's:
I'm a Cat
The Cat says meow
The dog says bow wow
The animal makes a sound
This example show Polymorphism and inheritance concept using single ArrayList.
The list is of animals. Of the Super Class type.
A dog is also an animal, a cat is also an animal (by inheritance) so you can add them to the Animal List.
If you want to refer a particular object (like the Cat in the example code), you have to use 'instance of' operator for Casting.
for more info you can read about Inheritance and Polymorphism.
You can do like this or similar to this.
Models:
Animal:
public class Animal {
Dog dog;
Cat cat;
public Animal(Dog dog, Cat cat) {
this.dog = dog;
this.cat = cat;
}
public Animal() {
}
public Dog getDog() {
return dog;
}
public void setDog(Dog dog) {
this.dog = dog;
}
public Cat getCat() {
return cat;
}
public void setCat(Cat cat) {
this.cat = cat;
}
Dog:
public class Dog {
String name;
String age;
String food;
public Dog(String name, String age, String food) {
this.name = name;
this.age = age;
this.food = food;
}
public String getFood() {
return food;
}
public void setFood(String food) {
this.food = food;
}
Cat:
public class Cat {
String name;
String age;
String breed;
public Cat(String name, String age, String breed) {
this.name = name;
this.age = age;
this.breed = breed;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
MainActivity.java:
public class TestActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test);
Animal animal = new Animal();
animal.setDog(new Dog("tomi", "6","Roti"));
List<Animal> animals = new ArrayList<>();
animals.add(animal);
Log.d("Jay", animals.toString());
}
What you are askings reffers to polymorphism. It means subclass inherits everything from it's superclass.
To achieve what you want you would create your objects like:
Animal dog = new Dog();
((Dog) dog).setBreed("Terrier"); //This is called Casting
...
Animal cat = new Cat();
...
And then in your ListView when showing data you can check if your object is instance of particular object, like this:
if(dog instanceof Dog)
textView.setText(((Dog) dog).getBreed());
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");
}
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";
}
}
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));
}
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;
}