From the graph we can see that this is an inherited, animal class is the parent class, cats, wolves, dogs can inherit some of the properties of the parent class, for example:
Animal following properties:
- eye
- ear
- nose
Wolves, cats, dogs, unique property for its cry
Then the following Java code to implement inheritance description
Code
package cn.test.logan.day10; /** * Parent animal * @author QIN * * / Public class Animal { public String name; Private String Eye; // Private modified property, not inherited by subclasses public String Ears; Age String; // default attributes, if cross-package, the subclass can not inherit public void say(){ } public void eat(){ System.out.println ( "eat ..." ); } }
package cn.test.logan.day10; /** * Use the extends keyword to indicate to the specified parent class inherit * So CatAnimal to have properties and methods of the parent class Animal * @author QIN * * / Public class CatAnimal the extends Animal { // override the parent class method say @Override public void say () { System.out.println("喵喵喵"); } public void catchMouse(){ System.out.println ( "a catch mice" ); } }
package cn.test.logan.day10; /** * Test class * @author QIN * * / Public class the Test { public static void main (String [] args) { // a first method of creating an object: creating a subclass object CatAnimal, with reference to the variable type CatAnimal CatAnimal catAnimal = new new CatAnimal (); // The second way to create an object: a supertype of a reference variable subclass object @ disadvantages: the object can not be used to create special properties and methods of the subclasses // Animal catAnimal1 new new CatAnimal = (); // catAnimal.catchMouse (); // can use this method // catAnimal1.catchMouse (); // can not be used catAnimal.name = "A little" ; System.out.println(catAnimal.name); } }