Follow
Publications: 22 | Followers: 0

CISC181lect8(inheritance)

Publish on Category: Birds 0

Inheritence
Put classes into a hierarchyderive a new class based on an existing classwith modifications or extensions.Avoiding duplication and redundancyClassesinthelower hierarchy is called asubclass(orderived,child,extended class).A class in the upper hierarchy is called asuperclass(orbase,parent class).Place all common variables and methods in the superclassPlace specialized variables and methods in the subclassesredundancyreduced as common variables and methods are not repeated in all the subclasses.
In java, you use the word “extends” in the class definition to indicate a class is a subclass of another class, e.g.,class GoalkeeperextendsSoccerPlayer{......}classChemStudentextendsStudent {.....}class CylinderextendsCircle {......}
public class Circle{private double radius;private doublecircumference;private doublearea;publicCircle(){this(3.1);}public Circle(double rad) {radius = rad;circumference =getCirc();area =getArea();}public doublegetRad() {return radius;}public voidsetRad(double rad) {radius = rad;circumference =getCirc();area =getArea();}public doublegetCirc() {return (2.0 *radius *Math.PI);}public doublegetArea() {return(radius * radius *Math.PI);}}
public class Cylinderextends Circle{private double height;// Private field for only Cylinder objectspublicCylinder(double radius, double h) {//Constructorsuper(radius);// invoke superclass' constructorheight= h;}public Cylinder(double h) {super();height = h;}public doublegetHeight() {return height;}public voidsetHeight(double h) {height = h;}public doublegetVolume() {returngetArea()*height;// Use Circle'sgetArea()}}public static void main(String[]args) {Circle x = new Circle(4.2);System.out.format("Circle Area: %5.2f\n",x.getArea());System.out.format("Circle Circumference: %5.2f\n",x.getCirc());Cylinder y = new Cylinder(3.0, 2.0);System.out.format("Cylinder Area: %5.2f\n",y.getArea());System.out.format("Cylinder Circumference: %5.2f\n",y.getCirc());System.out.format("Cylinder Volume: %5.2f\n",y.getVolume());}
Circle Area: 55.42Circle Circumference: 26.39Cylinder Area: 28.27Cylinder Circumference: 18.85Cylinder Volume: 56.55
public class Animal {publicbooleanisaPet;public String name;public Animal() {isaPet= true;name = "Fred";}public Animal(booleanpet, String name) {isaPet= pet;this.name = name;}public void sleep() {System.out.println("Animal is sleeping");}public void talk() {System.out.println("talking");}}public class Dog extends Animal{public String breed;publicDog(){super();breed = “Mutt”}public Dog(Stringname, String breed){this(true,name,breed);}public Dog(booleanpet, Stringname, String breed){super(pet, name);this.breed= breed;}public void move() {System.out.println("Frolicking forward");}}

publicclassmainAnimal{public static void main(String[]args) {Animalan_x= new Animal();System.out.println(an_x.name);System.out.println(an_x.isaPet);an_x.sleep();an_x.talk();Doga_dog= new Dog("Spot“,”pug”);System.out.println(a_dog.name);System.out.println(a_dog.isaPet);System.out.println(a_dog.breed);a_dog.sleep();a_dog.talk();a_dog.move();}}What fields and methods are part ofan_x?What fields and methods are part ofa_dog?
Do you see a problem?
class A {public A(intx) {}}class B extends A {public B() {}}class C {publicstatic void main(String[]args) {Bb= new B();}}
public class Animal {publicbooleanisaPet;public String name;public Animal() {isaPet= true;name = "Fred";}public Animal(booleanpet, String name) {isaPet= pet;this.name = name;}public void sleep() {System.out.println("Animal is sleeping");}public void talk() {System.out.println("talking");}}public class Dog extends Animal{public String breed;publicDog(){super();breed = “Mutt”}public Dog(Stringname, String breed){this(true,name,breed);}public Dog(booleanpet, Stringname, String breed){super(pet, name);this.breed= breed;}public void move() {System.out.println("Frolicking forward");}public voidtalk(){System.out.println(“bark bark");}}

publicclassmainAnimal{public static void main(String[]args) {Animalan_x= new Animal();System.out.println(an_x.name);System.out.println(an_x.isaPet);an_x.sleep();an_x.talk(); // what does this line do?Doga_dog= new Dog("Spot“,”pug”);System.out.println(a_dog.name);System.out.println(a_dog.isaPet);System.out.println(a_dog.breed);a_dog.sleep();a_dog.talk(); // what does this line do?a_dog.move();}}What methods and fields doesa_doghave?What happens whena_dog.talk() is executed?
Overriding!
When in a subclass you write a method that overrides a method with the same name in its parent class.In essence, you’ve got a default method in the superclassAnd then you have a more specific (and accurate) method belonging to the subclassEvery subclass can have its own default method that overrides the superclass’s method
public class Animal {publicbooleanisaPet;public String name;public Animal() {isaPet= true;name = "Fred";}public Animal(booleanpet, String name) {isaPet= pet;this.name = name;}public void sleep() {System.out.println("Animal is sleeping");}public void talk() {System.out.println("talking");}}public class Dogextends Animal{public Dog(){super();}public Dog(String name) {super(true, name);}public Dog(booleanpet, String name) {super(pet, name);}public void move() {System.out.println("Frolicking forward");}public void talk() {System.out.println("bark bark");}}

public class Wolfextends Dog{public Wolf(){super(false,"noName");}public void move() {System.out.println("running intently");}public void stalk() {System.out.println("stalking my prey");}public void talk() {System.out.println("howl");super.talk();}}publicclassmainAnimal{public static void main(String[]args) {Animalan_x= new Animal();// what methods and fields are available toan_x?Doga_dog= new Dog("Spot");// what methods and fields are available toa_dog?Wolfa_wolf= new Wolf();// what methods and fields are available toa_wolf?}}
public class Animal {publicbooleanisaPet;public String name;public Animal() {isaPet= true;name = "Fred";}public Animal(booleanpet, String name) {isaPet= pet;this.name = name;}public void sleep() {System.out.println("Animal is sleeping");}public void talk() {System.out.println("talking");}}public class Dogextends Animal{public String breed;publicDog(){super();breed = “Mutt”;}public Dog(String name) {super(true, name);breed = “Mutt”;}public Dog(booleanpet, Stringname, String breed){super(pet, name);this.reed= breed;}public void move() {System.out.println("Frolicking forward");}public void talk() {System.out.println("bark bark");}}

public class Wolfextends Dog{public Wolf(){super(false,"noName“, “wolf”);}public void move() {System.out.println("running intently");}public void stalk() {System.out.println("stalking my prey");}public void talk() {System.out.println("howl");super.talk();}}publicclassmainAnimal{public static void main(String[]args) {Animalan_x= new Animal();System.out.println(an_x.name);System.out.println(an_x.isaPet);an_x.sleep();an_x.talk();Doga_dog= new Dog("Spot");System.out.println(a_dog.name);System.out.println(a_dog.isaPet);a_dog.sleep();a_dog.talk();a_dog.move();Wolfa_wolf= new Wolf();System.out.println(a_wolf.name);System.out.println(a_wolf.isaPet);a_wolf.sleep();a_wolf.talk();a_wolf.move();a_wolf.stalk();}}
Coolness:
Animal[]an_arr= new Animal[3];an_arr[0]=an_x;an_arr[1] =a_dog;an_arr[2] =a_wolf;for (int i = 0; i < 3; i++) {an_arr[i].talk();if (an_arr[i].isaPet) {System.out.println(an_arr[i].name);}}// what gets printed?// couldI doan_arr[i].breed? (breed is a field in the dog class)// can I doan_arr[1].breed?
Only methods and fields in superclass can be accessed automatically:
Animal[]an_arr= new Animal[3];an_arr[0]=an_x;an_arr[1] =a_dog;an_arr[2] =a_wolf;for (int i = 0; i < 3; i++) {an_arr[i].talk();if (an_arr[i].isaPet) {System.out.println(an_arr[i].name);}}Dogtempd= (Dog)an_arr[1];System.out.println(tempd.breed);
Overriding
public class Musician {public void play(){System.out.println(“silence”);}}public class Drummer extends Musician {public void play() {System.out.println(“boom boom”);}}public class Guitarist extends Musician {public void play(){System.out.println(“twang”);}}
...Musicianmusician= new Guitarist();musician.play();What is the output?twang
Overriding
public class Musician {public void play(){System.out.println(“silence”);}}public class Drummer extends Musician {public void play(){System.out.println(“boom boom”);}}public class Guitarist extends Musician {public void play(){System.out.println(“twang”);super.play();}}
...Musicianmusician= new Guitarist();musician.play();musician = new Drummer();musician.play();What is the output?twangsilenceboomboom
public class Animal {publicbooleanisaPet;public String name;publicbooleanisaWolf;public Animal() {this(true,"Fred",false);}public Animal(booleanpet, String name) {this(pet,name,false);}public Animal(booleanpet, String name,booleanisawolf) {isaPet= pet;this.name = name;this.isaWolf=isawolf;}public void sleep() {System.out.println("Animal is sleeping");}public void talk() {System.out.println("talking");}}
public class Dog extends Animal {booleanisaDog= true;public Dog(){super();}public Dog(String name) {super(true, name);}public Dog(booleanpet, String name) {super(pet, name);}public void move() {System.out.println("Going forward");}public void talk() {System.out.println("bark bark");}}
public class Wolf extends Dog {public Wolf(){super(false,"noName",true);}public void move() {System.out.println("running intently");}public void stalk() {System.out.println("stalking my prey");}public void talk() {System.out.println("howl");super.talk();}}…Wolf x = new Wolf();Animal x = new Wolf();
Will this work?
How can we fix this?
public class Animal {publicbooleanisaPet;public String name;publicbooleanisaWolf;public Animal() {this(true,"Fred",false);}public Animal(booleanpet, String name) {this(pet,name,false);}public Animal(booleanpet, String name,booleanisawolf) {isaPet= pet;this.name = name;this.isaWolf=isawolf;}public void sleep() {System.out.println("Animal is sleeping");}public void talk() {System.out.println("talking");}}
public class Dog extends Animal {booleanisaDog= true;public Dog(){super();}public Dog(String name) {super(true, name);}public Dog(booleanpet, String name) {super(pet, name);}public Dog(booleanpet, Stringname,booleanisawolf) {super(pet,name,isawolf);}public void move() {System.out.println("Going forward");}public void talk() {System.out.println("bark bark");}}
public class Wolf extends Dog {public Wolf(){super(false,"noName",true);}public void move() {System.out.println("running intently");}public void stalk() {System.out.println("stalking my prey");}public void talk() {System.out.println("howl");super.talk();}}…Wolf x = new Wolf();Animal x = new Wolf();
Public/Private and inheritance
Public:Anything in the superclass that is declared public is available to all subclasses (and everything else)Private – only the superclass has access to itSubclasses don’t have access
public class Animal {publicbooleanisaPet;public String name;public Animal() {this(true,"Fred",false);}public Animal(booleanpet, String name) {this(pet,name,false);}publicvoid talk() {System.out.println("talking");}}
public class Dog extends Animal {booleanisaDog= true;public Dog(){super();}public Dog(String name) {super(true, name);}public Dog(booleanpet, String name) {super(pet, name);}publicvoid talk() {System.out.println(name+“ says barkbark");}}
This works
public class Animal {publicbooleanisaPet;privateString name;public Animal() {this(true,"Fred",false);}public Animal(booleanpet, String name) {this(pet,name,false);}publicvoid talk() {System.out.println("talking");}}
public class Dog extends Animal {booleanisaDog= true;public Dog(){super();}public Dog(String name) {super(true, name);}public Dog(booleanpet, String name) {super(pet, name);}publicvoid talk() {System.out.println(name+“ says barkbark");}}
This doesn’t work – use a getter
public class Animal {publicbooleanisaPet;privateString name;public Animal() {this(true,"Fred",false);}public Animal(booleanpet, String name) {this(pet,name,false);}publicStringgetName(){return(name);}publicvoid talk() {System.out.println("talking");}}
public class Dog extends Animal {booleanisaDog= true;public Dog(){super();}public Dog(String name) {super(true, name);}public Dog(booleanpet, String name) {super(pet, name);}publicvoid talk() {System.out.println(getName()+“ says barkbark");}}
This works
How many problems do you see?
public class Circle {double radius;publicCircle(doubleradius) {radius = radius;}public doublegetRadius() {return radius;}public doublegetArea() {return radius * radius *Math.PI;}}public class B extends Circle {double length;publicB(doubleradius,double length) {Circle(radius);}public doublegetArea() {returngetArea() * length;}}
Abstract Methods
Suppose you have many class behaviors that have a common first step and a common last stepThe middle step isdifferentWouldn’t it be nice if you could write this code once:public voidcommonBehavior() {// ... code that does first stepdoMiddleStep();// ... code that does last step}
You can!
public voidcommonBehavior() {// ... code that does first stepdoMiddleStep();// ... code that does last step}publicabstractvoiddoMiddleStep();
Abstract Classes
Declared using theabstractkeywordabstract classCannot beinstantiated (can’t make an object from this class)Must be a superclass to other classesfields, methods and constructorsareaccessed in the same way as with the othersubclasses.abstract methodsmethods without any implementationmustbe overridden by asubclass // forces you to write a definition of the method in the subclassAbstract methods can be implemented within the abstract classAclass must be abstract if it has abstractmethods
abstractclass Animal {publicbooleanisaPet;public String name;public Animal() {this(true,"Fred");}publicAnimal(booleanpet, Stringname){isaPet= pet;this.name = name;}publicStringgetName(){return name;}abstractvoid talk();public void talking() {System.out.print(“The animal says ");talk();System.out.println(“ and then it is quiet.”)}}
public class Dog extends Animal {booleanisaDog= true;public Dog(){super();}public Dog(String name) {super(true, name);}public Dog(booleanpet, String name) {super(pet, name);}publicvoid talk() {System.out.println("bark bark");}}
public classMain{public static void main(String[]args) {Doga_dog= new Dog("Spot");a_dog.talking();}}…The animal says: barkbarkand thenitis quiet
What is output?
Which of these is legal?
public class abstract A {abstract void unfinished();}
class A {abstractvoid unfinished();}
abstract class A {void unfinished();}
abstract class A {void unfinished() {}}
A
B
C
D
E
Interfaces
containsonly constants and abstract methodsUnlike abstract classes they cannot havefields (properties)or implementedmethods(methods with code in them)
29
29
Define an Interface
To distinguish an interface from a class, Java uses the following syntax to define an interface:
publicinterfaceInterfaceName{constant declarations;//constants!! Things you give a value to and never touch again other//than to use the valuemethod signatures;}
Example:
publicinterfaceEdible {/** Describe how to eat */public abstract StringhowToEat();public abstract StringhowToDrink();public abstract BooleanisEdible(Foodfooditem);}
Why Interfaces?
Remember, all subclasses of an interface must implement (make code for) each method in the interface
31
31
Laziness
Allfields in an interface MUST BEpublicstatic(e.g., constants)AllmethodsMUST BEpublicabstractForthis reason, these modifiers can be omitted, as shown below:
A constant defined in an interface can be accessed using syntaxInterfaceName.CONSTANT_NAMEe.g.,T1.K
publicinterfaceAnimalInterface{abstractpublicString talks();abstractpublicString eats();abstractpublicString moves();}
classCatimplementsAnimalInterface{publicCat(){}publicString talks(){return("meow meow");}publicString eats(){return("Eats mice");}publicString moves(){return("prowls");}}
publicclassBunnyimplementsAnimalInterface{publicBunny() {}publicString talks(){return("no idea");}publicString eats(){return("Eats hay");}publicString moves(){return("hops");}}
publicclassCowimplementsAnimalInterface{publicCow() {}publicString talks(){return("moo moo");}publicString eats(){return("Eats grass");}publicString moves(){return("rarely runs");}}publicstaticvoidmain(String[]args) {AnimalInterface[]arr=newAnimalInterface[3];arr[0] =newCow();arr[1] =newCat();arr[2] =newBunny();for(AnimalInterfacex:arr) {System.out.println(x.talks());System.out.println(x.moves());System.out.println(x.eats());}}
Using interfaces
Interfaces are not part of the class hierarchyA class mayimplementmany different interfacesPolymorphism still holdsAn instance of class X that implements interface Y can be used as the base interface type:Y myY = new X();
publicinterfaceAnimalInterface{abstractpublicString talks();abstractpublicString eats();abstractpublicString moves();}
publicinterfaceFarmThings{abstractpublicbooleanisaFarmTool();abstractpublicString produces();}
publicclassCowimplementsAnimalInterface,FarmThings{publicCow() {}publicString talks(){return("moo moo");}publicString eats(){return("Eats grass");}publicString moves(){return("rarely runs");}publicbooleanisaFarmTool(){returnfalse;}publicString produces(){return"milk";}

0

Embed

Share

Upload

Make amazing presentation for free
CISC181lect8(inheritance)