Logo 
Search:

Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

abstract class question

  Asked By: Kevin    Date: Mar 07    Category: Java    Views: 1030
  

I have an abstract class, say Animal, with a constructor that
relies on an abstract method. When I create my child class
I declare the method. Will this work? Can the super-class
call methods in the child-class?

Share: 

 

1 Answer Found

 
Answer #1    Answered By: Burkett Bernard     Answered On: Mar 07

abstract class  Animal extends Object{
String type = "";

public Animal(){
setType();
}

public abstract  void setType();
public abstract String getType();

}

class Giraffe extends Animal{

public void setType(){
type = "Giraffe";
}
public String getType(){
return type;
}
}

class Cheetah extends Animal{

public void setType(){
type = "Cheetah";
}
public String getType(){
return type;
}
}

class Gazelle extends Animal{

public void setType(){
type = "Gazelle";
}
public String getType(){
return type;
}
}

public class Test{
public static void main(String[] args){
(new Test()).test();
}

public void test(){
Animal[] animals = new Animal[10];
animals[0] = (Animal)new Giraffe();
animals[1] = new Cheetah();
animals[2] = new Gazelle();
animals[3] = new Giraffe();
animals[4] = new Cheetah();
animals[5] = new Gazelle();
animals[6] = new Cheetah();
animals[7] = new Cheetah();
animals[8] = new Giraffe();

for (int i = 0; i < animals.length;i++){
if (animals[i] == null) {
System.out.println("Not initialized.");
} else{
if (animals[i] instanceof
Giraffe) System.out.println("animals[" + i + "] is a Giraffe");
if (animals[i] instanceof
Cheetah) System.out.println("animals[" + i + "] is a Cheetah");
if (animals[i] instanceof
Gazelle) System.out.println("animals[" + i + "] is a Gazelle");
if (animals[i] instanceof Cheetah)
System.out.println("animals[" + i + "] is an Animal");
}
}
}
}

 
Didn't find what you were looking for? Find more on abstract class question Or get search suggestion and latest updates.




Tagged: