Inherited Classes in Java CSCI 392 Classes - Part 2
Recap from last week… Scope of Fields and Methods can be Constructors public, private, protected Constructors syntax is just like C++ optional since fields can be initialized "static" fields and methods belong to the entire class, not individual instances
What is Inheritance? Building a new class by reusing everything in an existing class. Subclasses can add to their base class's list of methods and fields, and can also replace inherited methods. Animal Fish Mammal
Why use Inheritance? So that you don't have to rewrite a bunch of code. Better Maintenance: Correcting/Improving code in the base class fixes all the subclasses.
Declaring an Inherited Class public class stack extends list { The new stack class is a subclass of the list class
What gets Inherited? All fields marked as "protected" or "public". "private" fields are only visible to the class that declared them "protected" fields are only visible to the class that declared them, and any subclasses All methods marked protected or public.
public class list { protected int[] values; private int size; ... public class stack extends list public void some_method () values[i] = myinteger; // legal size++; // illegal
Jargon Alert Overloading Overriding creating multiple methods with the same name example: multiple constructors may have the same name if they have different parameters Overriding replacing inherited methods example: see next page
Override Overload public class SuperClass { public void method1 () { ... } public void method1 (int param1) public void method2 () } public class SubClass extends SuperClass public void method2 (int param2) Override Overload
public class SuperClass { public void method1 () { ... } public void method1 (int param1) public void method2 () } public class SubClass extends SuperClass public void method2 (int param2) ... SubClass bob = new SubClass(); bob.method1(); bob.method2(); bob.method1(99);
Using the Parent's Constructor public class ParentClass { public ParentClass (int param) { do a bunch of work } ... } ================================== public class ChildClass extends ParentClass public ChildClass (int param) super (param)