80 likes | 190 Views
Интерфейсы и наследование. Интерфейсы. Объявление public interface OperateCar { // constant declarations, if any // method signatures int turn(Direction direction , double radius, double startSpeed ); int changeLanes (Direction direction , double startSpeed , double endSpeed );
E N D
Интерфейсы • Объявление • public interface OperateCar { • // constant declarations, if any • // method signatures • intturn(Direction direction, double radius, double startSpeed); • intchangeLanes(Direction direction, double startSpeed, double endSpeed); • } • Реализация • public class OperateBMW760i implements OperateCar { • // the OperateCar method signatures, with implementation ,for example: • intsignalTurn(Direction direction, booleansignalOn) { • // code to turn BMW's LEFT turn indicator lights on • // code to turn BMW's LEFT turn indicator lights off • } • // other members, as needed -- for example, helper classes not // visible to clients of the interface • }
Расширение • Интерфейсов public interface GroupedInterface extends Interface1, Interface2, Interface3 { // constant declarations // base of natural logarithms double E = 2.718282; // method signatures void doSomething (int i, double x); intdoSomethingElse(String s); }
Наследование public class Bicycle { //implement } public class MountainBike extends Bicycle { // the MountainBike subclass adds one field public intseatHeight; // the MountainBike subclass has one constructor public MountainBike(intstartHeight, intstartCadence, intstartSpeed, intstartGear) { super(startCadence, startSpeed, startGear); seatHeight = startHeight; } }
Приведениетипов MountainBikemyBike = new MountainBike(0, 0, 0, 0); Object obj = new MountainBike(0, 0, 0, 0); MountainBikemyBike1 = (MountainBike)obj; if (objinstanceofMountainBike) { MountainBikemyBike2 = (MountainBike)obj; }
Полиморфизм ДемоTestBike
Final и Астрактны Классы • Final final class ChessAlgorithm { enumChessPlayer { WHITE, BLACK } ... finalChessPlayergetFirstPlayer() { return ChessPlayer.WHITE; } ... } • Abstract public abstract class GraphicObject { // declare fields // declare non-abstract methods abstract void draw(); }