Mais conteúdo relacionado
Semelhante a 10 abstract (6)
Mais de Program in Interdisciplinary Computing (20)
10 abstract
- 1. We Know This Is Legal LIS4930 © PIC myDog Dog Dog Dog object These two are the same type. Dog myDog= new Dog()
- 2. AND we know this is legal LIS4930 © PIC myDog Dog Animal Dog object These two are not the same type. Animal myDog= new Dog()
- 3. BUT is this legal? LIS4930 © PIC myDog Animal Animal Animal object These two are the same type, but… what the heck does an Animal object look like? Animal myDog= new Animal()
- 4. Turn in your Textbooks. LIS4930 © PIC Look at pages 200 – 210 in the textbook
- 5. Some classes should not be instantiated! In other words, to stop anyone from saying “new” on that type. By marking the class as abstract, the compiler will stop any code, anywhere, from ever creating an instance of that type. You can still use that abstract type as a reference type – as a polymorphic argument or return type, or to make a polymorphic array. LIS4930 © PIC
- 6. Concrete vs. Abstract Concrete classes are those that are specific enough to be instantiated. A concrete class just means that it’s OK to make objects of that type. An abstract class means that nobody can ever make a new instance of that class. LIS4930 © PIC
- 7. Making Classes Abstract LIS4930 © PIC abstract public class Canine extends Animal { public void roam(); } public class MakeCanine { public void go() { Canine c; c = new Wolf(); c = new Canine(); c.roam(); } } Compilation Error abstract Animal makeNoise() eat() sleep() roam() Canine roam() Wolf makeNoise() eat()
- 8. LIS4930 © PIC Making Methods Abstract abstract public class Canine extends Animal { public abstract void roam(); public void hunt() { //go hunting } } public class Wolf extends Canine { public void roam() { System.out.println(“Roam in MT”); } Canine c; c = new Wolf(); c = new Canine(); c.roam(); c.hunt(); } } Compilation Error ALL abstract methods MUST be overridden! abstract Animal makeNoise() eat() sleep() abstract Canine roam() hunt() Wolf makeNoise() eat() roam()