Slaid FP301 OOP 3.4 Apply Inheritance in Java program UPLOAD
Slaid FP301 OOP 3.4 Apply Inheritance in Java program UPLOAD
4
• A subclass inherits all the members (fields, methods, and
nested classes) from its superclass.
6
• Consider Student and Teacher as two classes.
• The details of a student are name, age, gender and mark in
different subjects.
• The details of a teacher are name, age, gender, subject
handled and salary.
• To store and manipulate the details of students and
teachers, two classes should be created.
• In one class you store the details of students and in
another class you store the details of teachers as shown in
Figure below
7
class Student{ class Teacher{
String name; String name, subject;
int age; int age;
char gender; char gender;
double mark; double salary;
8
4.3.1 Describe inheritance in Java
programs.
class Person{
String name;
int age;
char gender;
}
10
Single Inheritance
Subclass
Class B
11
Multiple Inheritance
Super class
Class C Subclass
Multi-Level Inheritance
Definition: Multi-Level Inheritance is the extension of Single
Inheritance. When a class is inherited from another
subclass, then it is Multi-Level Inheritance.
Class A Super class
Class B
Subclass for Super class for
Class A Class C
Class C
Subclass
A very important fact to remember is that Java only supports only
single inheritance.
This means that a class cannot extend more than one class.
20
File SubKelas.java
public class SubKelas extends Superkelas {
public void StatusKelas(){
super.statusKelas();
System.out.println("Dalam Sub Kelas");
}}
File TestSuperSubKelas.java
public class TestSuperSubKelas {
public static void main(String[] args) {
SubKelas s = new SubKelas();
s.StatusKelas();
s.method1Superkelas();
}} 21
3.4.3 Explain overriding method in Java programs
23
• The argument list should be exactly the same as that of the
overridden method.
• The return type should be the same or a subtype of the
return type declared in the original overridden method in
the super class.
• Instance methods can be overridden only if they are
inherited by the subclass.
• A method declared final cannot be overridden.
• A method declared static cannot be overridden but can be
re-declared.
• If a method cannot be inherited then it cannot be
overridden.
24
3.4.4 Implement overriding method in Java programs.
Example Method overiding:
File IlmuHisab.java
public class IlmuHisab {
int no1;
int no2;
int jaw;
void tambah(){
jaw=no1 + no2;
System.out.println("Dalam Superkelas IlmuHisab: Jaw =
"+jaw);
}}
25
File OperasiTambah.java Inheritance
26
File TestOveriding.java
27