Im trying to illustrate uses of instance vs static field members.
Just for myself to see how they work, and i think i have done this succesfully. But is there a way i can (for the sake of code reusability) only create one copy of get and set methods that i have defined in my classes, so i dont have to define them for every class? Would an interface be the logical way to go?
Code:/* this is a test to see if a static member is diffrent from an instance member. */ public class Test{ public static void main(String[] args){ Car NSX = new Car(); Boat Fountain = new Boat(); // show defalults System.out.println("Max mph for your car is" + NSX.getMaxMPH()); System.out.println("Max rpm for your car is" + NSX.getMaxRPM()); System.out.println(); System.out.println("Max mph for your boat is" + Fountain.getMaxMPH()); System.out.println("Max rpm for your boat is" + Fountain.getMaxRPM()); System.out.println(); NSX.setMaxRPM(9000); // set new RMP for Boat also, since redline is shared among // all instances; System.out.println("Max mph for your car is" + NSX.getMaxMPH()); System.out.println("Max rpm for your car is" + NSX.getMaxRPM()); System.out.println(); System.out.println("Max mph for your boat is" + Fountain.getMaxMPH()); System.out.println("Max rpm for your boat is" + Fountain.getMaxRPM()); System.out.println(); NSX.setMaxMPH(230); // just set MPH for car since mph is an instance member. System.out.println("Max mph for your car is" + NSX.getMaxMPH()); System.out.println("Max rpm for your car is" + NSX.getMaxRPM()); System.out.println(); System.out.println("Max mph for your boat is" + Fountain.getMaxMPH()); System.out.println("Max rpm for your boat is" + Fountain.getMaxRPM()); System.out.println(); } } class Vehicle{ protected int mph; protected static int redline; public Vehicle(int mph, int redline){ this.mph = mph; this.redline = redline; } } class Car extends Vehicle{ public Car(int mph, int redline){ super(mph,redline); this.mph = mph; this.redline = redline; } public Car(){ this(200,6500); // defualts } public int getMaxRPM (){ return redline; } public int getMaxMPH(){ return mph; } public void setMaxRPM(int setRPM){ this.redline = setRPM; } public void setMaxMPH(int setMPH){ this.mph = setMPH; } } class Boat extends Vehicle{ Boat(int mph, int redline){ super(mph,redline); this.mph = mph; this.redline = redline; } public Boat(){ this(120,6500); // defualts } public int getMaxRPM(){ return redline; } public int getMaxMPH(){ return mph; } public void setMaxRPM(int setRPM){ this.redline = setRPM; } public void setMaxMPH(int setMPH){ this.mph = setMPH; } }


Reply With Quote
