1
LẬP TRINH HƯỚ NG ĐÔ
́
I TƯỢNG TRONG JAVA
phần 2
IV.
A
1. Khai ba
́
o kế thư
̀
a
.
,
-
(SuperClass : )
-
(SubClass)
p cha
class ClassName extends SuperClass
{ //Member Variables Declarations, Methods
}
-
,
-
.
,
.
2. Viết chồ ng ha
̀
m hay che khuấ t ha
̀
m (Overriding Methods)
,
,
,
. Khi
( ) v
.
V d :
. L
toString, .
2
3. Tư
̀
khoa
́
super
.
,
.
a
.
:
- 1 : .
,
cha c: classname()
:
super(Parameter-List)
Parameter-
.
super()
con
:
class MyPoint {
int x, y;
MyPoint(int x, int y) {
this.x = x;
this.y = y;
}
void display() {
\
}
}
class MyPoint2 extends MyPoint {
int z;
String name;
MyPoint2(int x, int y, int z, String name) {
super(x,y); // Kh2 ,
this.z = z; //
this.name = name;
3
}
void display() { // Vi
\
}
}
- 2 : :
super.Member
:
() trong class MyPoint2, c:
void display() {
super.display();
\
}
V. , PH
.
.
, .
,
abs
abstract [Type] MethodName(Parameter-List) ;
,
.
, .
,
.
V d :
, , ,
,
(, )
nh vi (
,
, ).
Graphic.
, nên
,
,
4
abstract class GraphicObject {
int x, y;
. . .
void moveTo(int newX, int newY) {
. . .
}
abstract void draw();
}
ircle,
class Circle extends GraphicObject {
void draw() {
. . .
}
}
class Rectangle extends GraphicObject {
void draw() {
. . .
}
}
VI.
(
), (K
)
1. Sư
̉
dụng tư
̀
khoa
́
final cấ m sự chồ ng lắ p
Java,
.
,
: class Box {
double width;
double height;
double depth;
final double volume() {
5
return width * height * depth;
}
. . .
}
2. Sư
̉
dụng tư
̀
khoa
́
final cấ m sự kế thư
̀
a
, .
, .
V d : final class Box { . . .
}
VII.
.
(Nested Class) :
class EnclosingClass{ //
. . .
static class StaticNestedClass { //
. . .
}
class InnerClass { //
. . .
}
}
.
.
,
. Tuy nhiên,
.
: .
L (static nested class)
.
6
bao, .
. H
L (nonstatic nested class )
,
(inner class).
.
class Outer {
int outer_x = 100;
void test() {
Inner inner = new Inner();
inner.display_x();
}
class Inner { // uter
int inner_y = 10;
void display_x() {
}
}
void display_y() { // không th
}
}
class InnerClassDemo {
public static void main(String args[]) {
Outer outer = new Outer();
outer.test();
}
}