Handout 4 Basic Inheritance Info Hiding Overloading

You might also like

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

Basics of class,

inheritance methods
and constructors,
Information Hiding and
method overloading
Java methods

•A method must be in a class in java


programming language
•Methods contain actions or functions a
class can perform.
•Arguments are used to provide external
data required by function perform its
functions
•When you call (invoke) a method java
runtime tries to find the method with
required signature
•The data is provided in method signature
in terms of parameters, their data types
and order
Syntax of method
Information_hiding_type static return_type method name(type[e.g. int]
parameter/argument) {

Statements
//Return return_type value/variable // if method //return type is not void it
must have return //statement
}
Class constructors
A class must have the following characteristics
1. Class constructors have same name as class
2. Class constructors are called when object is
created
3. Class constructors don’t return a value so they
cannot return type
• When program creates an instance of a class
(object) java invokes class constructor.
• The constructor is called only once when
object is created with the operator new.
• We have used new when creating Scanner
objects for inputting data. Scanner(System.in)
is constructor for scanner class
Write a program that creates an account object and uses constructor to
initialize the balance and display the balance.
Acount class will have balance class field
Class Fees1 with a constructor
package fees;
public class Fees {
double balance;
String name;
int age;

Fees(double bl, String nm, int ag) { // class constructor method


//constructor called only once when object created.
//initializing class variables
balance = bl;
name= nm;
age= ag;
}
public static void main(String[] args) {
Fees f = new Fees(50000, "Mandela", 26); //creating object
System.out.println("Student name:"+f.name);
}
}
Class Fees2 with main invoking comments method and constructor
package fees;
public class Fees {
double balance;
String name;
int age;
Fees(double bl, String nm, int ag) { // class constructor method
//initializing class variables
balance = bl;
name= nm;
age= ag;
}
public static String comments(double bal){
String mess=null;
if(bal>90000)
mess="over limit";
else
mess="within limit";
return mess;
}
public static void main(String[] args) {
Fees f = new Fees(50000, "Mandela", 26); //creating variable
System.out.println("Student name:"+f.name);
System.out.println("balance:"+f.balance);
System.out.println("Balance type:"+comments(80000));
}
}
super keyword
Super should be must first method(statement)
in subclass constructor. Super method is used
to call parent/super class constructors
If method is overridden in a subclass then we
have two methods
A subclass cannot override its parent class
constuctor.
• E.g. ReducedFees(double bl, String nm, int ag) cannot
override Fees(double bl, String nm, int ag)
• Super keyword with . Separator is used to access methods
of parent or ancestor class
• Super method is used to invoke constructor of immediate
parent class
• If subclass doesn’t invoke super class constructor in first
line of subclass constructor java immediately invokes no
argument constructor
• Invoking a parametrized constructor we use
super(parameterlist)
super keyword sub class program
package fees;
public class ReducedFees extends Fees{
ReducedFees(double bl, String nm, int
ag) {
super(bl,nm,ag);
//adding methods specific to constructor
System.out.println("Special fees
reductions");
System.out.println(super.name);
}

}
this keyword
This keyword is used when you want to refer to instance of a variable from its class.
Previous fees1 names of constructor were different from those of class variables
Program below need this keyworld to differential constructor parameter names and class variable as the have
same names
Class Fees with a constructor
package fees;
public class Fees {
double balance;
String name;
int age;
Fees(double bal, String name, int age) { // class constructor method
//initializing class variables
/* this enable differentiating balance for class and balance parameter passed to constructor*/
this.balance = balance ;
this.balance = balance ;
this.age= age;
}
public static void main(String[] args) {
Fees f = new Fees(50000, "Mandela", 26); //creating variable
System.out.println("Student name:"+f.name);
}
}
Inheritance - extends

•extends is a keyword that is used to


implement inheritance. The subclass
inherits the properties of parent
(super) class and may also define its
own attributes
•Save in two classes in same file and
introduce a static variable in subclass,
display variable in superclass by sub
class. variablename see the results?
Inheritance
• Inheritance is mechanism that allow sub/child classes
to inherit members of an existing class called
parent/superclass
• Inheritance enables one to save time during program
development
• The class from which sub class inherits from is called a
super/parent class. The inheriting class is called sub
class/child (C++ refers to super class as base class and
sub class as derived class)
• Subclass can add its own methods and fields
• Java supports only single inheritance but some
programming language support multiple inheritance
• In java programming language all classes begins (inherit
from) with object class of java.lang.object which every
java class inherits from or extends
Inheritance

Object

Account
Scanner
Java inheritance & UML symbol
•UML use an arrow with triangle arrow
head
•Lower classes inherit methods form upper
classes as indicated by inheritance symbol
•Employeestudent are students who are
also employeee. E.g. some students may be
employees. staffFalculty - E.g. PhD
students may be lecturers. These are two
examples of double inheritance.
•Java doesn’t support multiple inheritance
C++ Common Lisp support multiple
inheritance.
Java inheritance & UML symbol
•UML use an arrow with triangle arrow
head
•Lower classes inherit methods form upper
classes as indicated by inheritance symbol
•Employeestudent are students who are
also employeee. E.g. some students may be
employees. staffFalculty - E.g. PhD
students may be lecturers. These are two
examples of double inheritance.
•Java doesn’t support multiple inheritance
C++ Common Lisp support multiple
inheritance.
Community members UML class diagram
CommunityMember
-memberName
-memberName

`` Alumus
Student
Employee -memberName
-memberName
-memberName
-memberName -memberName
-memberName
-memberName

EmployeeStudent
`Falculty Staff
-memberName
-memberName -memberName -memberName
-memberName -memberName

StaffFalcuty
-memberName
-memberName
Java and multiple inheritance
•Java doesn’t support multiple
inheritance C++ Common Lisp support
multiple inheritance.
•Multiple inheritance allows a class to
inherit from more than one class
•Java designers thought benefits of
multiple inheritance were not worthy
increased complexity caused by
increased complexity
•C++ and Java designers had different
perspective on benefits and costs of
multiple inheritance.
Java and interfaces
•Java has interfaces feature enables
achieving some goals of multiple
inheritances
•An interface is method without an
implementation
•A class implements an interface by
providing the method implementation
•interface is Java keyword used to
create interfaces
Information hiding

•Java public keyword (in UML +) – A class


public members can be accessed by
members of other classes
•Java private keyword (In UML -) - A
class private members are only available
accessible within the class
•Java protected keyword (In UML #) – a
protected access offers intermediate
level between private and public. super
class protected members are accessible
by members super class and members of
sub class.
Inheritance program
Save as superclass.java
public class superclass extends mtotoclass {
public static void main(String[] args) {
System.out.println("print hello from Superclass");
csub(); }
}

Save as mtotoclass.java
public class mtotoclass {
public static void csub() {
System.out.println("print hello from mtoto class");
} }
Method overloading

•It’s a way of implementing polymorphism


and is called method overloading.
•methods have same name but arguments
passed are of different data types or
have different number of arguments or
the order of arguments is different.
•Methods cannot be distinguished by
return types int square(int x) {} and
double square(double x){}. Why does float
give error?
Method overloading program
public class overload
{
public static void main(String[] args) {
System.out.println(andika(12));
System.out.println(andika(8.9));
System.out.println(andika(5, 100));
}

public static String andika(int i) {


return ("Integer passed is " + i);
}

public static String andika(double f) {


return ( "float passed is " + f);
}

public static String andika(int i1, int i2) {


return ("product sum is " + (i1*i2));
} }
TestCourse CLASS PROGRAM
package testcourse;
public class TestCourse {
public static void main(String[] args) {
Course course1 = new Course("Data Structures");
Course course2 = new Course("Database Systems");
course1.addStudent("Peter Jones");
course1.addStudent("Brian Smith");
course1.addStudent("Anne Kennedy");
course2.addStudent("Peter Jones");
course2.addStudent("Steve Smith");
System.out.println("Number of students in course1: "
+ course1.getNumberOfStudents());
String[] students = course1.getStudents();
for (int i = 0; i < course1.getNumberOfStudents(); i++)
System.out.print(students[i] + ", ");
System.out.println();
System.out.print("Number of students in course2: "
+ course2.getNumberOfStudents());
} }
Course CLASS PROGRAM
package testcourse;
public class Course {
private String courseName;
private String[] students = new String[100];
private int numberOfStudents;
public Course(String courseName) {
this.courseName = courseName;
}

public void addStudent(String student) {


students[numberOfStudents] = student;
numberOfStudents++;
}

public String[] getStudents() {


return students;
}
public int getNumberOfStudents() {
return numberOfStudents;
}
public String getCourseName() {
return courseName;
}
public void dropStudent(String student) {
// Left as an exercise in Exercise 9.9
} }
Writing the programs
•Create a testcourse project with
TestCourse class
•FileNew
Projectjavaapplication
•To create course class
•FileNew filejavajava class
•Type course class name: Course
Gratuity program description
•An organization has two types of
employees managers and contract
employees
•Managers are paid monthly bonus but
not overtime. Managers are in charge
of department. Managers are paid
gratuity 2% of salary after 5 years
calculated as 0.02*5*12*salary
•Contract employees are paid overtime
but not bonus. Contract employees
are paid gratuity 1% of salary after 3
years calculated as 0.01* 3*12*salary.
Contract employees belong to a
section.
gratuity class diagram
Employee
-name:string
-empid:string
-salary:double
-gratuity:double
+setName():void
+getName():string
+setEmpid():void
+getEmpid():string
+setSalary():void
+getSalary():double
+setGratuity():void
+getGratuity():double

ContractEmployee
Manager
-section:string
-department:string -overtime:double
-bonus:double +setSection():void
+setDepartment():void +getSection():string
+getDepartment():string +setovertime():void
+setBonus():void +getOvertime():double
+getBonus():double
Creating Gratuity program
•We implement as four classes
1. GratuitySystemTest that will
contain main class
2. Employee
3. Manager
4. ContractEmployee

You might also like