Courses‎ > ‎AP Computer Science‎ > ‎Konstantinovich‎ > ‎notes‎ > ‎

2017-10-13

posted Oct 13, 2017, 6:08 AM by Konstantinovich Samuel   [ updated Oct 13, 2017, 12:39 PM ]
Its FRIDAY! (Triskaidekaphobia be damned!)

Quiz. (12 minutes)

Objects -> Constructors


public class A{
    private int x;
    //default constructor sets x to 
    //a predetermined value
    
    //this constructor is automatically
    //called by subclass constructors
    public A(){
x = 10;
    }
    

    //alternate constructor uses a 
    //parameter for the value
    public A(int value){
x = value;
    }

    //accessor getX returns x.
    //void method to print the getX
    

    public int getX(){
return x;
    }

    //toString will call the most recently
    //updated version of getX
    public String toString(){
return "" + getX();
    }
}


public class B extends A{
    //Test the default constructor
    public B(){
//when you do not call any super constructor
//java will insert a call to super();
//super(9001);
    }
    //add a new constructor, call super
    //Test Yell
    //Override getX to be a negation
    public int getX(){
return -1 * super.getX();//call to parent class method
//since you are overriding it.
    }
    //Test Yell now!
 
}


public class DriverAB{
    
    public static void main(String[]args){
System.out.println("ObB:");
B obB1 = new B();
System.out.println(obB1.getX());

//toString of B is inherited from A.
System.out.println(obB1);

System.out.println("ObA:");
A obA1 = new A();
System.out.println(obA1.getX());


A obA2 = new A(99);
System.out.println(obA2.getX());
    }
}

Comments