Object oriented day 8:
Review:
-
Interface:
Reference data type, interface definition, can only contain constants and abstract methods
Cannot be instantiated, needs to be implemented, implementation class: all abstract methods must be overridden
A class can implement multiple interfaces, separated by commas. If it inherits and implements again, it should inherit first and then implement
Interfaces can inherit interfaces
Meaning: encapsulate the common attributes and behaviors of some derived classes -- realize multi inheritance
It is a standard and a specification
Notes:
1. Polymorphism:
Methods (behavior is method) are also polymorphic;
(1) Performance:
① When the same object is modeled into different types, it has different functions
-----Polymorphism of objects: I, you, water... All objects are polymorphic (experience tomorrow)
② Features: when a reference of the same type points to different objects, it has different implementations
-----Polymorphism of behavior: cut(), move(), getImage(), getScore() - all abstract methods are polymorphic
people p1 = new barber(); people p2 = new surgeon();
(2) Upward modeling / automatic type conversion: seaobject 0 = new Battleship();
① A reference to a supertype points to an object of a derived class
② What you can point out depends on the type of reference: P1 cut(); p2. cut();
③ There are two data types that can be modeled: superclass + implemented interface
(3) There are only two conditions for the success of forced type conversion:
① The object pointed to by the reference is the type
② Refers to the object that implements the interface or inherits the class
(4) If the above conditions are not met during forced conversion, ClassCastException type conversion exception occurs
Suggestion: before forced conversion, first judge whether the referenced object is of this type through instanceof
package ooday08; public class MultiTypeDemo { public static void main(String[] args){ /* There are only two conditions for successful forced type conversion: ①The object (Boo()) pointed to by reference o is the type (Boo type) "Data type reference type variable = new object " Data type: Aoo Reference: refers to the object Boo from the reference type variable pointing to: equal sign = object: new ②Refers to the object that implements the interface or inherits the class */ Aoo o = new Boo(); //The object of o is Boo Boo o1 = (Boo)o; //① The object to which reference o refers is of type Boo. [it is wrong to assign o to Boo, because o is Aoo. It needs to be forced to turn from large to small. Add (Boo) to the front of O] Inter o2 = (Inter)o; //② Reference the object pointed to and implement the Inter interface //Coo o3 = (Coo)o; //- Runtime ClassCastException type conversion exception if(o instanceof Coo){ //false, judge first Coo o4 = (Coo)o; //Re strong turn }else{ System.out.println("o no Coo type"); } /* System.out.println(o instanceof Boo);//true System.out.println(o instanceof Inter);//true System.out.println(o instanceof Coo);//false */ } } interface Inter{} class Aoo{} class Boo extends Aoo implements Inter{} class Coo extends Aoo{}
Supplement:
-
Interfaces can inherit multiple interfaces:
interface Inter1{ void show(); } interface Inter2{ void test(); } interface Inter3 extends Inter1,Inter2{ void say(); }
-
When do I need a forced rotation?
----The attribute / behavior to be accessed does not exist in the superclass, so it must be forcibly converted. The instanceof judgment must be made before forcibly converting
-
ArrayIndexOutOfBoundsException: array subscript out of bounds exception
NullPointerException: null pointer exception
ClassCastException: type conversion exception
-
This picture will be used in operation 2. Collision between deep-water bomb and submarine:
Object oriented day 8 job:
1. Mine entry: second half
2. Collision between deep-water bomb and submarine
3. Drawing points and drawing life
1. Mine entry: the second half.. Reference code:
package cn.tedu.submarine; import javax.swing.JFrame; import javax.swing.JPanel; //1. import java.awt.Graphics; import java.util.Timer; import java.util.TimerTask; import java.util.Random; import java.util.Arrays; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; /** The whole game world */ public class World extends JPanel { //2. public static final int WIDTH = 641; /** Width of window */ public static final int HEIGHT = 479; /** Window height */ //The following pile is the objects displayed in the window private Battleship ship = new Battleship(); //warship private SeaObject[] submarines = {}; //Submarine (reconnaissance submarine, torpedo submarine, mine submarine) array private Mine[] mines = {}; //Mine array private Bomb[] bombs = {}; //Deep water bomb array /** Generate submarine (reconnaissance submarine, torpedo submarine, mine submarine) objects */ public SeaObject nextSubmarine(){ Random rand = new Random(); //Random number object int type = rand.nextInt(20); //0 to 19 if(type<10){ //From 0 to 9, the reconnaissance submarine object is returned return new ObserveSubmarine(); }else if(type<15){ //10 to 14, return to the torpedo submarine object return new TorpedoSubmarine(); }else{ //At 15 to 19, return to the mine submarine object return new MineSubmarine(); } } private int subEnterIndex = 0; //Submarine admission count /** Submarines (reconnaissance submarines, torpedo submarines and mine submarines) enter the site */ public void submarineEnterAction(){ //Walk every 10 milliseconds subEnterIndex++; //Increase by 1 every 10 milliseconds if(subEnterIndex%40==0) { //Walk every 400 (40 * 10) milliseconds SeaObject obj = nextSubmarine(); //Get submarine object submarines = Arrays.copyOf(submarines,submarines.length+1); //Capacity expansion submarines[submarines.length-1] = obj; //Add obj to the last element of submarines } } private int mineEnterIndex = 0; //Mine admission count /** Mine entry */ public void mineEnterAction(){ //Walk every 10 milliseconds mineEnterIndex++; //Increase by 1 every 10 milliseconds if(mineEnterIndex%100==0){ //Walk every 1 second (100 * 10) for(int i=0;i<submarines.length;i++){ //Traverse all submarines if(submarines[i] instanceof MineSubmarine){ //If the submarine is a mine submarine MineSubmarine ms = (MineSubmarine)submarines[i]; //Converting submarines to mine submarines Mine obj = ms.shootMine(); //Acquire mine object mines = Arrays.copyOf(mines,mines.length+1); //Capacity expansion mines[mines.length-1] = obj; //Add obj to the last element } } } } /** Ocean object movement */ public void moveAction(){ //Walk every 10 milliseconds for(int i=0;i<submarines.length;i++){ //Traverse all submarines submarines[i].move(); //Submarine movement } for(int i=0;i<mines.length;i++){ //Traverse all mines mines[i].move(); //Mine movement } for(int i=0;i<bombs.length;i++){ //Traverse all deep-water bombs bombs[i].move(); //Deep water bomb movement } } /** Delete out of bounds ocean objects */ public void outOfBoundsAction(){ //Walk every 10 milliseconds for(int i=0;i<submarines.length;i++){ //Traverse all submarines if(submarines[i].isOutOfBounds()){ //It's out of bounds submarines[i] = submarines[submarines.length-1]; //Replace the cross-border submarine with the last element submarines = Arrays.copyOf(submarines,submarines.length-1); //Shrink volume (shrink the last element) } } for(int i=0;i<mines.length;i++){ //Traverse all mines if(mines[i].isOutOfBounds()){ //It's out of bounds mines[i] = mines[mines.length-1]; //Replace the transboundary mine with the last element mines = Arrays.copyOf(mines,mines.length-1); //Shrink volume (shrink the last element) } } for(int i=0;i<bombs.length;i++){ //Traverse all deep-water bombs if(bombs[i].isOutOfBounds()){ //It's out of bounds bombs[i] = bombs[bombs.length-1]; //Replace the cross-border bomb with the last element bombs = Arrays.copyOf(bombs,bombs.length-1); //Shrink volume (shrink the last element) } } } /** Start program execution */ public void action(){ KeyAdapter k = new KeyAdapter() { //Not required /** Override keyReleased() key lift event */ public void keyReleased(KeyEvent e) { //When the key is lifted, it will be triggered automatically - it is not required to master if(e.getKeyCode()==KeyEvent.VK_SPACE){ //If the space bar is raised -- it is not required to master Bomb obj = ship.shoot(); //Get depth bomb object bombs = Arrays.copyOf(bombs,bombs.length+1); //Capacity expansion bombs[bombs.length-1] = obj; //Add obj to the last element of the bombs } if(e.getKeyCode()==KeyEvent.VK_LEFT){ //If the left button head is raised -- it is not required to master ship.moveLeft(); //The warship moved left } if(e.getKeyCode()==KeyEvent.VK_RIGHT){ //If the right button head is raised -- it is not required to master ship.moveRight(); //Warship shift right } } }; this.addKeyListener(k); //Not required Timer timer = new Timer(); //Timer Objects int interval = 10; //Timing interval (in milliseconds) timer.schedule(new TimerTask() { public void run() { //Something done regularly (occurs automatically every 10 milliseconds) submarineEnterAction(); //Submarines (reconnaissance submarines, torpedo submarines and mine submarines) enter the site mineEnterAction(); //Mine entry moveAction(); //Ocean object movement outOfBoundsAction(); //Delete out of bounds ocean objects repaint(); //Redraw (call paint() again) } }, interval, interval); //Timing plan } /** Rewrite paint() g: Brush */ public void paint(Graphics g){ //Walk every 10 milliseconds Images.sea.paintIcon(null,g,0,0); //Draw an ocean map ship.paintImage(g); //Painted warship for(int i=0;i<submarines.length;i++){ //Traverse submarine array submarines[i].paintImage(g); //Draw submarine } for(int i=0;i<mines.length;i++){ mines[i].paintImage(g); } for(int i=0;i<bombs.length;i++){ bombs[i].paintImage(g); } } public static void main(String[] args) { JFrame frame = new JFrame(); //3. World world = new World(); world.setFocusable(true); frame.add(world); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(WIDTH+16, HEIGHT+39); frame.setLocationRelativeTo(null); frame.setVisible(true); //1) Set the window visible 2) call the paint() method as soon as possible world.action(); //Start program execution } } //Note: there are no changes in other categories, which are omitted here
2. The collision between a deep-water bomb and a submarine.. Reference code:
package day08; import javax.swing.ImageIcon; import java.awt.Graphics; import java.util.Random; //Ocean object public abstract class SeaObject { public static final int LIVE = 0; public static final int DEAD = 1; protected int state = LIVE; //current state protected int width; protected int height; protected int x; protected int y; protected int speed; public SeaObject(int width,int height){ this.width = width; this.height = height; x = -width; Random rand = new Random(); y = rand.nextInt(World.HEIGHT-height-150)+150; speed = rand.nextInt(3)+1; } public SeaObject(int width,int height,int x,int y,int speed){ this.width = width; this.height = height; this.x = x; this.y = y; this.speed = speed; } public abstract void move(); public abstract ImageIcon getImage(); public boolean isLive(){ return state==LIVE; } public boolean isDead(){ return state==DEAD; } public void paintImage(Graphics g){ if(isLive()){ this.getImage().paintIcon(null,g,x,y); } } /** Detect submarine crossing */ public boolean isOutOfBounds(){ return x>= World.WIDTH; //x> = window width, that is, it is out of bounds } /** Collision detection */ public boolean isHit(SeaObject other){ //Suppose this refers to a submarine and other refers to a bomb int x1 = this.x-other.width; //x1: submarine x-bomb width int x2 = this.x+this.width; //x2: submarine x + submarine width int y1 = this.y-other.height; //y1: submarine y-bomb height int y2 = this.y+this.height; //y2: submarine y + submarine height int x = other.x; //x: Bomb x int y = other.y; //y: Bomb y return x>=x1 && x<=x2 && y>=y1 && y<=y2; //If x is between x1 and x2, and y is between y1 and y2, it means collision } /** Ocean objects die */ public void goDead(){ state = DEAD; //Change the status to DEAD } } package day08; import javax.swing.ImageIcon; //warship public class Battleship extends SeaObject { private int life; public Battleship(){ super(66,26,270,124,20); life = 5; } public void step(){ System.out.println("Warship movement"); } public ImageIcon getImage(){ return Images.battleship; } public Bomb shoot(){ return new Bomb(this.x,this.y); } public void moveLeft(){ x-=speed; } public void moveRight(){ x+=speed; } public void addLife(int num){ life += num; } } package day08; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.Graphics; import java.util.Arrays; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; //The whole game world public class World extends JPanel { public static final int WIDTH = 641; public static final int HEIGHT = 479; private Battleship ship = new Battleship(); //warship private SeaObject[] submarines = {}; //Submarine (reconnaissance submarine, torpedo submarine, mine submarine) private Mine[] mines = {}; //mine private Bomb[] bombs = {}; //Deep water bomb /** Randomly generated submarine */ public SeaObject nextSubmarine(){ Random rand = new Random(); int type = rand.nextInt(20); if(type<10){ return new ObserveSubmarine(); }else if(type<15){ return new TorpedoSubmarine(); }else{ return new MineSubmarine(); } } private int subEnterIndex = 0; /** Submarine admission */ public void submarineEnterAction(){ //Walk every 10 milliseconds subEnterIndex++; if(subEnterIndex%40==0){ //Every 40 milliseconds SeaObject obj = nextSubmarine(); submarines = Arrays.copyOf(submarines,submarines.length+1); submarines[submarines.length-1] = obj; } } private int mineEnterIndex = 0; /** Mine (torpedo, mine) entry */ public void MineEnterAction(){ mineEnterIndex++; if(mineEnterIndex%100==0){ for(int i=0;i<submarines.length;i++){ if(submarines[i] instanceof MineSubmarine){ MineSubmarine ms = (MineSubmarine)submarines[i]; Mine obj = ms.shootMine(); mines = Arrays.copyOf(mines,mines.length+1); mines[mines.length-1] = obj; } } } } /** Ocean object movement */ public void moveAction(){ for(int i=0;i<submarines.length;i++){ submarines[i].move(); } for(int i=0;i<mines.length;i++){ mines[i].move(); } for(int i=0;i<bombs.length;i++){ bombs[i].move(); } } /** Delete out of bounds objects */ public void outOfBoundsAction(){ for(int i=0;i<submarines.length;i++){ if(submarines[i].isOutOfBounds() || submarines[i].isDead()){ submarines[i] = submarines[submarines.length-1]; submarines = Arrays.copyOf(submarines,submarines.length-1); } } for(int i=0;i<mines.length;i++){ if(mines[i].isOutOfBounds() || mines[i].isDead()){ mines[i] = mines[mines.length-1]; mines = Arrays.copyOf(mines,mines.length-1); } } for(int i=0;i<bombs.length;i++){ if(bombs[i].isOutOfBounds() || bombs[i].isDead()){ bombs[i] = bombs[bombs.length-1]; bombs = Arrays.copyOf(bombs,bombs.length-1); } } } private int score = 0; //Player score //Collision between deep-water bomb and submarine public void bombBangAction(){ for(int i=0;i<bombs.length;i++){ Bomb b = bombs[i]; for(int j=0;j<submarines.length;j++){ SeaObject s = submarines[j]; if(b.isLive() && s.isLive() && s.isHit(b)){ b.goDead(); s.goDead(); if(s instanceof EnemyScore){ EnemyScore es = (EnemyScore)s; score += es.getScore(); } if(s instanceof EnemyLife){ EnemyLife ea = (EnemyLife)s; int num = ea.getLife(); ship.addLife(num); } } } } } /** Start the operation of the program */ public void action(){ KeyAdapter k = new KeyAdapter(){ public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_SPACE){ Bomb obj = ship.shoot(); //Deep water bomb admission bombs = Arrays.copyOf(bombs,bombs.length+1); bombs[bombs.length-1] = obj; } if(e.getKeyCode() == KeyEvent.VK_LEFT){ ship.moveLeft(); } if(e.getKeyCode() == KeyEvent.VK_RIGHT){ ship.moveRight(); } } }; this.addKeyListener(k); Timer timer = new Timer(); int interval = 10; timer.schedule(new TimerTask() { public void run() { submarineEnterAction(); //Submarines (reconnaissance, mines, torpedoes) enter the site MineEnterAction(); //Mine entry moveAction(); //Ocean object movement outOfBoundsAction(); //Delete out of bounds objects bombBangAction(); //Collision between deep-water bomb and submarine repaint(); } }, interval, interval); } public void paint(Graphics g){ Images.sea.paintIcon(null,g,0,0); //Draw an ocean map ship.paintImage(g); for(int i=0;i<submarines.length;i++){ submarines[i].paintImage(g); } for(int i=0;i<mines.length;i++){ mines[i].paintImage(g); } for(int i=0;i<bombs.length;i++){ bombs[i].paintImage(g); } } public static void main(String[] args) { JFrame frame = new JFrame(); World world = new World(); world.setFocusable(true); frame.add(world); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(WIDTH+16, HEIGHT+39); frame.setLocationRelativeTo(null); frame.setVisible(true); world.action(); } } //Note: there are no changes in other categories, which are omitted here
3. Draw points and draw life.. Reference code:
package day08; import javax.swing.ImageIcon; //warship public class Battleship extends SeaObject { private int life; public Battleship(){ super(66,26,270,124,20); life = 5; } public void step(){ System.out.println("Warship movement"); } public ImageIcon getImage(){ return Images.battleship; } public Bomb shoot(){ return new Bomb(this.x,this.y); } public void moveLeft(){ x-=speed; } public void moveRight(){ x+=speed; } public void addLife(int num){ life += num; } public int getLife(){ return life; } } package day08; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.Graphics; import java.util.Arrays; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.awt.event.KeyAdapter; import java.awt.event.KeyEvent; //The whole game world public class World extends JPanel { public static final int WIDTH = 641; public static final int HEIGHT = 479; private Battleship ship = new Battleship(); //warship private SeaObject[] submarines = {}; //Submarine (reconnaissance submarine, torpedo submarine, mine submarine) private Mine[] mines = {}; //mine private Bomb[] bombs = {}; //Deep water bomb /** Randomly generated submarine */ public SeaObject nextSubmarine(){ Random rand = new Random(); int type = rand.nextInt(20); if(type<10){ return new ObserveSubmarine(); }else if(type<15){ return new TorpedoSubmarine(); }else{ return new MineSubmarine(); } } private int subEnterIndex = 0; /** Submarine admission */ public void submarineEnterAction(){ //Walk every 10 milliseconds subEnterIndex++; if(subEnterIndex%40==0){ //Every 40 milliseconds SeaObject obj = nextSubmarine(); submarines = Arrays.copyOf(submarines,submarines.length+1); submarines[submarines.length-1] = obj; } } private int mineEnterIndex = 0; /** Mine (torpedo, mine) entry */ public void MineEnterAction(){ mineEnterIndex++; if(mineEnterIndex%100==0){ for(int i=0;i<submarines.length;i++){ if(submarines[i] instanceof MineSubmarine){ MineSubmarine ms = (MineSubmarine)submarines[i]; Mine obj = ms.shootMine(); mines = Arrays.copyOf(mines,mines.length+1); mines[mines.length-1] = obj; } } } } /** Ocean object movement */ public void moveAction(){ for(int i=0;i<submarines.length;i++){ submarines[i].move(); } for(int i=0;i<mines.length;i++){ mines[i].move(); } for(int i=0;i<bombs.length;i++){ bombs[i].move(); } } /** Delete out of bounds objects */ public void outOfBoundsAction(){ for(int i=0;i<submarines.length;i++){ if(submarines[i].isOutOfBounds() || submarines[i].isDead()){ submarines[i] = submarines[submarines.length-1]; submarines = Arrays.copyOf(submarines,submarines.length-1); } } for(int i=0;i<mines.length;i++){ if(mines[i].isOutOfBounds() || mines[i].isDead()){ mines[i] = mines[mines.length-1]; mines = Arrays.copyOf(mines,mines.length-1); } } for(int i=0;i<bombs.length;i++){ if(bombs[i].isOutOfBounds() || bombs[i].isDead()){ bombs[i] = bombs[bombs.length-1]; bombs = Arrays.copyOf(bombs,bombs.length-1); } } } private int score = 0; //Player score //Collision between deep-water bomb and submarine public void bombBangAction(){ for(int i=0;i<bombs.length;i++){ Bomb b = bombs[i]; for(int j=0;j<submarines.length;j++){ SeaObject s = submarines[j]; if(b.isLive() && s.isLive() && s.isHit(b)){ b.goDead(); s.goDead(); if(s instanceof EnemyScore){ EnemyScore es = (EnemyScore)s; score += es.getScore(); } if(s instanceof EnemyLife){ EnemyLife ea = (EnemyLife)s; int num = ea.getLife(); ship.addLife(num); } } } } } /** Start the operation of the program */ public void action(){ KeyAdapter k = new KeyAdapter(){ public void keyPressed(KeyEvent e) { if(e.getKeyCode() == KeyEvent.VK_SPACE){ Bomb obj = ship.shoot(); //Deep water bomb admission bombs = Arrays.copyOf(bombs,bombs.length+1); bombs[bombs.length-1] = obj; } if(e.getKeyCode() == KeyEvent.VK_LEFT){ ship.moveLeft(); } if(e.getKeyCode() == KeyEvent.VK_RIGHT){ ship.moveRight(); } } }; this.addKeyListener(k); Timer timer = new Timer(); int interval = 10; timer.schedule(new TimerTask() { public void run() { submarineEnterAction(); //Submarines (reconnaissance, mines, torpedoes) enter the site MineEnterAction(); //Mine entry moveAction(); //Ocean object movement outOfBoundsAction(); //Delete out of bounds objects bombBangAction(); //Collision between deep-water bomb and submarine repaint(); } }, interval, interval); } public void paint(Graphics g){ Images.sea.paintIcon(null,g,0,0); //Draw an ocean map ship.paintImage(g); for(int i=0;i<submarines.length;i++){ submarines[i].paintImage(g); } for(int i=0;i<mines.length;i++){ mines[i].paintImage(g); } for(int i=0;i<bombs.length;i++){ bombs[i].paintImage(g); } g.drawString("SCORE: "+score,200,50); g.drawString("LIFE: "+ship.getLife(),400,50); } public static void main(String[] args) { JFrame frame = new JFrame(); World world = new World(); world.setFocusable(true); frame.add(world); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.setSize(WIDTH+16, HEIGHT+39); frame.setLocationRelativeTo(null); frame.setVisible(true); world.action(); } } //Note: there are no changes in other categories, which are omitted here