You are on page 1of 46

Object-oriented Programming

Language (JAVA)
(面向对象程序设计)

李建欣(Jianxin Li)
lijx@act.buaa.edu.cn
lijianxin@gmail.com
School of Computer,
Beihang University
© Beihang University
Chapter 3 Review
Primitive Data Types
Statement
Array

Reminding: http://graduate.buaa.edu.cn
Selecting your lesson firstly.

2
© Beihang University
Exercise (for everyone)
1. Writing a program to output followings:
1
12
123
1234
12345
123456
2. The results?

3
© Beihang University
A Question?

class A ...{ A a1 = new A();


public String show(D obj) A a2 = new B();
{ return ("A and D"); } B b = new B();
public String show(A obj)... C c = new C();
{ return ("A and A"); } } D d = new D();
System.out.println(a1.show(b)); ①
class B extends A...{ System.out.println(a1.show(c)); ②
public String show(B obj)... System.out.println(a1.show(d)); ③
{ return ("B and B"); } System.out.println(a2.show(b)); ④
public String show(A obj)... System.out.println(a2.show(c)); ⑤
{ return ("B and A"); } } System.out.println(a2.show(d)); ⑥
System.out.println(b.show(b)); ⑦
class C extends B...{} System.out.println(b.show(c)); ⑧
class D extends B...{} System.out.println(b.show(d)); ⑨

What is its output?

4
© Beihang University
Chapter-4

Java OOP Features

5
© Beihang University
Some key points in Java OOP

Object and Class


The Object Lifecycle
Class Creation
Overloading
Subclass

6
© Beihang University
Basic Concepts in OOP
 Three key features of OOP

Encapsulation ”封装 ”
form of software reusability
Polymorphism ”多态 ”
Write programs in a general fashion
to handle a wide variety of classes
Inheritance ” 继承 ”

7
© Beihang University
Class and Object
A class defines the variables and the methods
common to all objects of a certain kind.
Primitive data type
The abstracted date type can be realized with Java
class

Object is an instance of a class

8
© Beihang University
An Example of Java Class & Object
Class Definition:
Class EmpInfo{
String name;
String designation;
String department;
void print( ){ System.out.println(name+“is”+
designation+“at”+department);}
}
Object initialization:…
EmpInfo employee = new EmpInfo( );
employee.name = “ Robert Javaman”;
employee.designation = “Manager”;
employee.department = “Coffee shop”;
employee.print( ); ...
9
© Beihang University
The Lifecycle of Object

Creating an object

Using an object

Destroying an object

10
© Beihang University
Object Creation

Three steps to create an object:


 Declaration ”声明 ”
 Instantiation ”实例化”
 Initialization ” 初始化”

e.g.,:
Point origin_one ;
origin_one = new Point(23, 94);
Rectangle rect_one = new Rectangle(origin_one, 100, 200);
Rectangle rect_two = new Rectangle(50, 100);

11
© Beihang University
Object Instantiation Procedure
Constructing and initializing an object
Invoking new XXX();
Creating memory space (variable, method body, and
implemented code) and initializing variables member of
class
numerical value :0;
boolean: false;
String: null;
Explicit initialization: the variable declaration of class
includes some simple assignment expression
public class Initialized{
private int x = 5 ;
private String name = “Fred”;

 Construction function
} execution

12
© Beihang University
Garbage Collection
Garbage Collection: Java Running Environment
If an object will not been used, and delete it
If an object have no reference to it, it can be
collected as a garbage
Garbage Collector: A process involved in the JRE,
and the allocated memory of non-used object can
be released periodically.

13
© Beihang University
Garbage Collection

C++:Atype *a=new Atype( );


b c
Atype *b=a;
Atype *c=a;
// after a is used, then delete it (dangling pointer )
delete a;

Java :A a=new A( ); a b c
A b=a; b c
A c=a;
// delete it
a= null ;

14
© Beihang University
Creating an object
Creation of Class

15
© Beihang University
Constructor Function

Definition : public class name


(parameters){ … }

Note:
•The name of method must be the same as
the name of class.
•No return type

16
© Beihang University
Default Constructor
If there is no constructor function, a default
constructor will be invovled during the Java codes
compiling. For example, public Employee( ){ };
Once you declared a new constructor function, the
default constructor will not be involved into the
source code.

17
© Beihang University
Class Function Member
Format
<modifiers><return_type><name>
([<argument_list>])[throws <exception>]{<block>}

18
© Beihang University
Example:

public class PassTest{


float ptValue;
public PassTest(float x){
ptValue= x;
}
public static void main(String args[ ] ){
PassTest pt= new PassTest(10 );
System.out.println(“Int value is:” +pt.ptValue);
}
}

19
© Beihang University
Encapsulation of Data

Data Hiding: Using private to define variable, and


this variable can only be used in the function member.
Class Date{
public int day, month, year;
void setDate( int a, int b, int c){
day = a;
month = b;
year = c ;
}
}

Date d1;
d1 = new Date( );
d1.setDate(30,9,2001);
d1.day = 30;
...
20
© Beihang University
Encapsulation
One of the four fundamental OOP concepts
The other three are inheritance, polymorphism, and
abstraction.
A technique of making the fields in a class private
and providing access to the fields via public methods
,also referred to as data hiding.
It is a protective barrier that prevents the code and
data being randomly accessed by other code defined
outside the class. Access to the data and code is
tightly controlled by an interface.
The main benefit of encapsulation is
maintainability, flexibility and extensibility to our code.

21
© Beihang University
Example

22
© Beihang University
Why Encapsulation is Important
A real life example.
class BankAccounts{
public float AccountBalance;
…}
--------------------------------------------------------
myBankAccount.AccountBalance=-100; // without encapsulation
----------------------------------------------------------
Bool setAccountBalance(float amount) // with encapsulation
{
if (amount>=0 && someOtherConditions)
AccountBalance = amount;
return true;
else

return false;
}

23
© Beihang University
Keyword : this

Key words this is used to pointer the object itself


e.g.,:class Date {
private int day, month,year;
public Date getTommorrow( ){
this.day++;

}

24
© Beihang University
Keyword: super
Super is used to point to the superclass。

Public class Empolyee {


private String name ;
private int salary;
public String getDetails( ){
return “Name: ”+name+“\nSalary:”+salary;
}
}
public class Manager extends Empolyee {
private String department ;
public String getDetails( ){
return super.getDetailes( )+‘\nDepartment: “+
department;
}
}

25
© Beihang University
Subclass

Subclass is a belonging ( is a ) relation.


e.g.,:public class Employee { public class Manager {
String name ; String name ;
Date hireDate ; Date hireDate ;
Date dateofBirth ; Date dateofBirth ;
String jobTitle ; String jobTitle ;
int grade ; int grade ;
… String department ;
} Employee [ ] subordinates;

}

26
© Beihang University
Extends
Keyword extends is used.
public class Employee { public class Manager extends Employee
String name ; {
Date hireDate ;
String department ;
Date dateofBirth ;
String jobTitle ; Employee [ ] subordinates;
int grade ;
… }
}

Subclass is a method to create a new class


based on an existing class
27
© Beihang University
Subclass
Subclass can inherit the attributes, function of
Superclass, and subclass declares its own
special variables and functions
The variables and functions with private modifier
can not be inherited.
The constructor function can not be inherited
How to invoke the constructor in a method?
this();
How to invoke the constructor in a super class?
super();
super is a key work for get the super class.

28
© Beihang University
Invoking function of Superclass

class Employee{ ...


public Employee( String n){
name=n;
}
}
class Manager entends Emplyee{
public Manager( String s,String d){
super(s);
... }
}

29
© Beihang University
(重载)Overloading
In a class, one method can be defined many
times.
classScreen {
public void print( int i){ … }
public void print( float i){ … }
public void print( String str ){ … }
}
Principals:
• the list of parameter must be different to
distinguish difference function implementation.
•The return type and access modifier may be
same or different.
30
© Beihang University
(重写)Overriding
A subclass can modify the behaviors inherited from
super class
The return type, method name, parameter list must
be same with the methods defined in the super class

31
© Beihang University
Overriding Example

public class Stack


{
private Vector items;
// code for Stack's methods and constructor not shown
// overrides Object's toString method
public String toString() {
int n = items.size();
StringBuffer result = new StringBuffer();
result.append("[");
for (int i = 0; i < n; i++) {
result.append(items.elementAt(i).toString());
if (i < n-1) result.append(",");
}
result.append("]");
return result.toString();
}
} © Beihang University
32
Polymorphism

33
© Beihang University
Polymorphism

The dictionary definition of polymorphism refers


to a principle in biology in which an organism or
species can have many different forms or stages.
This principle can also be applied to object-
oriented programming and languages like the
Java language. Subclasses of a class can define
their own unique behaviors and yet share some
of the same functionality of the parent class.

34
© Beihang University
Polymorphism

Java permits the variable of superclass object can be the


variable of subclass object.
E.g.,:Employee e = new Manager( );
But use this variable (e.g., e), you only can access the
methods provided by the supercalss, the special method of
subclass will be hidden.
During the running time, the method is identified.
Employee e = new Manager();
e.getDetails();

35
© Beihang University
Polymorphism
Overloaded methods are methods with the same name
signature but either a different number of parameters or
different types in the parameter list. By defining a method for
handling each type of parameter you achieve the effect that
you want.
Overridden methods are methods that are redefined within
an inherited or subclass. They have the same signature and
the subclass definition is used.
Don't confuse the concepts of overloading and overriding.
 Overloading deals with multiple methods in the same class with the same
name but different signatures.
 Overriding deals with two methods, one in a parent class and one in a child
class, that have the same signature.
 Overloading lets you define a similar operation in different ways for different
data.
 Overriding lets you define a similar operation in different ways for different
object types.

36
© Beihang University
Polymorphism
Polymorphism is the capability of an action or method to do
different things based on the object that it is acting upon. This
is the third basic principle of object oriented programming.
Overloading and overriding are two types of polymorphism .
dynamic method binding.
Assume that three subclasses (Cow, Dog and Snake)
have been created based on the Animal abstract class,
each having their own speak() method.
Notice that although each method reference was to an
Animal (but no animal objects exist), the program is able to
resolve the correct method related to the subclass object
at runtime. This is known as dynamic (or late) method
binding.

37
© Beihang University
Polymorphism Example
public class AnimalReference{
public static void main(String args[])
Animal ref; // set up var for an Animal
Cow aCow = new Cow("Bossy"); // makes specific objects
Dog aDog = new Dog("Rover");
Snake aSnake = new Snake("Earnie");
// now reference each as an Animal
ref = aCow;
ref.speak();
ref = aDog;
ref.speak();
ref = aSnake;
ref.speak();
}

38
© Beihang University
Object class
Some methods can be overriding in the subclass of
Object
clone
equals
finalize
toString

39
© Beihang University
Object clone
aCloneableObject.clone();
aCloneableObject must implement Cloneable interface
Object.clone() is shallow copy, and not is deep copy

40
© Beihang University
Object.clone

public class Stack implements Cloneable {


private Vector items;
// code for Stack's methods and constructor not shown
protected Object clone() {
try {
Stack s = (Stack)super.clone(); // clone the stack
s.items = (Vector)items.clone(); // clone the vector
return s; // return the clone
} catch (CloneNotSupportedException e) { }
}
}

41
© Beihang University
Object.toString()
Return the string of an object representation .

E.g.,:
System.out.println(Thread.currentThread().toString());

Thread[main,5,main]

42
© Beihang University
Hashcode & equal

43
© Beihang University
Preparation
Package
Static
Abstract, Interface

44
© Beihang University
Following Chapters
Chapter 5
Essential JAVA Language

45
© Beihang University
46
© Beihang University

You might also like