Presentation is loading. Please wait.

Presentation is loading. Please wait.

Inherited Classes in Java

Similar presentations


Presentation on theme: "Inherited Classes in Java"— Presentation transcript:

1 Inherited Classes in Java
CSCI 392 Classes - Part 2

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

3 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

4 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.

5 Declaring an Inherited Class
public class stack extends list { The new stack class is a subclass of the list class

6 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.

7 public class list { protected int[] values; private int size; ... public class stack extends list public void some_method () values[i] = myinteger; // legal size++; // illegal

8 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

9 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

10 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);

11 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)


Download ppt "Inherited Classes in Java"

Similar presentations


Ads by Google