Objectives
- Create and use classes
- Create and use objects
- Discuss and examine access modifiers (public, private, protected, (package))
- Discuss and examine static vs. instance
- Use method overloading
- Use method overriding
class A { private static int count; // one copy shared by all A objects public int n1; protected int n2; private int n3; // only A has access to private members public A() { this(0, 0, 0); // calls other A constructor } public A(int a, int b, int c) { incrementCount(); n1 = a; n2 = b; setN3(c); } private void incrementCount() { count++; } public void setN3(int x) { if (x < 1) n3 = 1; else n3 = x; } public int getN3() { return n3; } public static int getCount() { return count; } } class B extends A { // B has inherited fields and methods from class A public double n4; public B() { super(7, 8, 9); // calls constructor for A n4 = 3.14; } public B(int i, int j, int k, double d) { super(i, j, k); // calls constructor for A n4 = d; } } A obj1 = new A(); B obj2 = new B(); B obj3 = new B(10, 20, 30, 5.2); // obj1.getCount() would return 3 // obj2.getCount() would return 3 // obj3.getCount() would return 3 // A.getCount() would return 3 // B.getCount() would return 3 // obj1.n1 would return 0 // obj2.n1 would return 7 // obj3.n1 would return 10 // obj1.n2 would return 0 // obj2.n2 would return 8 (if it works) // obj3.n2 would return 20 (if it works) // obj1.n3 would not work since n3 is private // obj2.n3 would not work since n3 is private // obj3.n3 would not work since n3 is private // obj1.getN3() would return 0 // obj2.getN3() would return 9 // obj3.getN3() would return 30 // obj1.n4 would not work // obj2.n4 would return 3.14 // obj3.n4 would return 5.2