package OOP; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.Scanner; import java.util.Vector; public class A { private String tenNV; private int tuoi; Scanner input = new Scanner(System.in); public A(String tenNV, int tuoi){ this.tenNV = tenNV; this.tuoi = tuoi; } public A() { } public String getTenNV() { return tenNV; } public void setTenNV(String tenNV) { this.tenNV = tenNV; } public String getTuoi() { return tuoi; } public void setTuoi(String tuoi) { this.tuoi = tuoi; } public ArrayList<A> input(int number){ ArrayList<A> alA = new ArrayList<A>(); for(int i = 0; i < number; i++){ System.out.println("tenNV:"); this.tenNV = input.nextLine(); System.out.println("tuoi:"); this.tuoi = Integer.parseInt(input.nextLine()); A a = new A(tenNV, tuoi); alA.add(a); } return alA; } @Override public String toString(){ return "tenNV: " + this.tenNV + " \ntuoi: " + this.tuoi; } }package arraylist; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import OOP.A; public class ArrayListDemo extends A{ public ArrayListDemo(){ } public static void SortArrayList(ArrayList<A> alA){ Comparator<A> compalA = new Comparator<A>() { @Override public int compare(A obj1, A obj2) { // so sanh chuoi // muon sap xep nguoc lai thi doi lai vi tri cua obj1 va obj2 return obj1.getTenNV().compareToIgnoreCase(obj2.getTenNV()); /* * Sap xep so * if(obj1.getTuoi() - obj1.getTuoi() > 0){ return 1; } else if(obj1.getTuoi() - obj1.getTuoi() < 0){ return -1; } else { return 0; } * * */ } }; Collections.sort(alA, compalA); } public static void displayData(ArrayList<A> alA){ for(A a : alA){ System.out.println(a.toString()); } } public static void main(String[] args) { ArrayListDemo alDemo = new ArrayListDemo(); ArrayList<A> alA = new ArrayList<A>(); alA = alDemo.input(3); SortArrayList(alA); displayData(alA); } }
Abstract class (Lớp trừu tượng) có thể hiểu là một class cha cho tất cả các Class có cùng bản chất. Do đó mỗi lớp con chỉ có thể kế thừa từ một lớp trừu tượng. Abstract class không cho phép tạo các thể hiện ( instance), vì vậy bạn không thể khởi tạo một đối tượng trực tiếp từ một Abstract class.
Interface có thể được xem như một mặt nạ cho tất cả các Class cùng cách thức hoạt động nhưng có thể khác nhau về bản chất. Từ đó lớp con có thể kế thừa từ nhiều Interface để bổ sung đầy đủ cách thức hoạt động của mình (đa kế thừa - Multiple inheritance).
| |||||||||||||||
Đối với những ai đã từng học qua về java chắc hẳn đều biết trong Java có rất nhiều kiểu dữ liệu như là char, int, long, float, Object, … Tuy nhiên tất cả những kiểu dữ liệu này đều có thể chia thành 2 kiểu dữ liệu cơ bản nhất đó là: Kiểu dữ liệu nguyên thủy (primitive type) và kiểu dữ liệu tham chiếu (reference type). Trong bài viết này chúng ta sẽ đi tìm hiểu về đặc điểm và các lưu ý khi sử dụng 2 kiểu dữ liệu cơ bản này.
1. Đầu tiên chúng ta sẽ tìm hiểu xem kiểu dữ liệu nguyên thủy và kiểu dữ liệu tham chiếu gồm nhưng kiểu dữ liệu nào:
- Kiểu dữ liệu nguyên thủy
Chắc hẳn các bạn cũng biết đến các kiểu dữ liệu cơ bản của hầu hết mọi ngôn ngữ lập trình như char, int, long, flloat, double, … Nhưng chắc cũng có bạn không biết rằng trong java tất cả các kiểu dữ liệu loại này đều là dữ liệu nguyên thủy. Cụ thể thì kiểu dữ liệu nguyên thủy bao gồm các loại dữ liệu sau:
- boolean
- int
- char
- long
- byte
- float
- short
- double
Dưới đây là sơ đồ các kiểu dữ liệu cơ bản:
- Kiểu dữ liệu tham chiếu
Vì chỉ có 2 kiểu dữ liệu là nguyên thủy và tham chiếu nên đương nhiên là những kiểu dữ liệu còn lại đều là kiểu dữ liệu tham chiếu rồi.
Một số ví dụ như là: Object, List, Array, … và tất nhiên tất cả các class mà bạn tạo ra đều là kiểu dữ liệu tham chiếu.
- boolean
- int
- char
- long
- byte
- float
- short
- double

Một số ví dụ như là: Object, List, Array, … và tất nhiên tất cả các class mà bạn tạo ra đều là kiểu dữ liệu tham chiếu.
2. Tiếp theo chúng ta sẽ phân tích đặc điểm của 2 kiểu dữ liệu cơ sở này:
Sự khác nhau cơ bản nhất của 2 kiểu dữ liệu cơ bản và nguyên thủy chính là cách thức mà chúng lưu trữ dữ liệu, bên cạnh đó các kiểu dữ liệu nguyên thủy đều không có các phương thức đi kèm, trong khi các kiểu dữ liệu tham chiếu đều các phương thức đi kèm ví dụ như ArrayList thì có add(), remove(), … Object thì có toString(), …
Cụ thể hơn, về cách lưu trữ dữ liệu:
- Kiểu dữ liệu nguyên thủy lưu trữ dữ liệu trong chính bản thân nó.
- Còn kiểu dữ liệu tham chiếu chỉ lưu trữ 1 giá trị là địa chỉ đến vùng nhớ mà nó tham chiếu đến. Các vùng nhớ này mới là nơi lưu trữ các thuộc tính của các đối tượng mà kiểu dữ liệu tham chiếu chỉ đến. (tương tự như khái niệm con trỏ trong C/C++ vậy)
Có vẻ khó hiểu nhỉ, để hiểu rõ hơn bạn có thể xem hình sau (chú ý đây chỉ là minh họa dễ hiểu, chỉ tương tự chứ không thật sự giống như cơ chế thật):
- Kiểu dữ liệu nguyên thủy: 2 biến X và Y có giá trị thực là 1 và 2, các giá trị thực này được nằm trong các ô nhớ tương ứng chứa X và Y chứ không cần tham chiếu tới vị trí khác.
- Kiểu dữ liệu tham chiếu: Obj có giá trị là @8 nghĩa là đối tượng mà Obj tham chiếu đến nằm ở ô nhớ thứ 8 trên bộ nhớ trong (RAM)
Đó là nói về lý thuyết còn trong quá trình lập trình thì các kiểu dữ liệu nguyên thủy và tham chiếu có khác biệt như thế nào?
Để thấy được sự khác biệt này ta cùng xét 1 ví dụ đơn giản:
Ví dụ về Kiểu dữ liệu nguyên thủy:
public static void main(String[] args) {
int x = 10;
int y = x;
System.out.println("Before assign");
System.out.println("x = "+x);
System.out.println("y = "+y);
y = 8; System.out.println("After assign");
System.out.println("x = "+x);
System.out.println("y = "+y);
}
Và đây là kết quả:
Before assign
X = 10
y = 10
After assign
X = 10y = 8
Bạn sẽ thấy rằng sau khi gán y=8 thì chỉ có giá trị của y thay đổi còn giá trị của x không thay đổi
Ví dụ về kiểu dữ liệu tham chiếu
public class ReferenceTypeExample {
int value = 10;
}
public static void main(String[] args) {
ReferenceTypeExample x = new ReferenceTypeExample();
ReferenceTypeExample y = x;
System.out.println("Before assign");
System.out.println("x = "+x.value);
System.out.println("y = "+y.value);
y.value = 8;
System.out.println("After assign");
System.out.println("x = "+x.value);
System.out.println("y = "+y.value);
}
Và đây là kết quả
Before assign
x = 10
y = 10
After assign
x = 8
y = 8
Bạn sẽ thấy rằng sau khi gán y.value=8 thì giá trị value của cả x và y đều thay đổi (trở thành 8).
Đây chính là sự khác biệt giữa kiểu dữ liệu tham chiếu và kiểu dữ liệu nguyên thủy đó.
Giải thích cho sự khác biệt này, vì kiểu dữ liệu nguyên thủy chứa dữ liệu ở trong chính ô nhớ của nó nên khi thay đổi y thì chỉ giá trị trong ô nhớ của y thay đổi mà giá trị trong ô nhớ của x không thay đổi. Còn đối với kiểu dữ liệu tham chiếu thì sau phép gán y=x, thì cả y và x sẽ cùng tham chiếu tới 1 ô nhớ, điều này làm cho khi thay đổi giá trị y.value chính là làm thay đổi giá trị value ở tại cái ô nhớ mà cả x và y cùng tham chiếu tới, nên khi x truy cập vào giá trị value của vùng nhớ đó thì giá trị này đã bị thay đổi do pháp gán y.value = 8
Chính vì sự khác biệt trên nên khi sử dụng kiểu dữ liệu tham chiếu các bạn cần cân nhắc để tránh trường hợp bị cập nhật giá trị không cần thiết.
Thông qua bài viết này, chắc hẳn các bạn đã hiểu được sự khác nhau cơ bản các kiểu dữ liệu nguyên thủy và tham chiếu.
Hẹn gặp lại các bạn trong các bài viết khác của mình.


int x = 10;
int y = x;
System.out.println("Before assign");
System.out.println("x = "+x);
System.out.println("y = "+y);
y = 8; System.out.println("After assign");
System.out.println("x = "+x);
System.out.println("y = "+y);
}
X = 10
y = 10
After assign
X = 10y = 8
int value = 10;
}
ReferenceTypeExample x = new ReferenceTypeExample();
ReferenceTypeExample y = x;
System.out.println("Before assign");
System.out.println("x = "+x.value);
System.out.println("y = "+y.value);
y.value = 8;
System.out.println("After assign");
System.out.println("x = "+x.value);
System.out.println("y = "+y.value);
}
x = 10
y = 10
After assign
x = 8
y = 8
1. Class A có 2 thuộc
tính:
String tenNV;
String diaChi;
và có 2 method input(); và showData();
- Có các phương thức get set cho từng thuộc tính.
- Có 2 constructor, một constructor không có tham số, và một constructor với hai tham số cho hai thuộc tính của lớp
- Các thành phần của lớp có thể được lớp khác thừa kế.
Note: - Phương thức final thì không được được thừa kế, và phương thức có từ khóa static củng vậy.
2. Class B extends class A
- Class B có thêm thuộc tính: int SDT;
- Class B có override method input(); and showData(); trong đó sử dụng thêm properties int SDT;
Class A
Class B
String tenNV;
String diaChi;
và có 2 method input(); và showData();
- Có các phương thức get set cho từng thuộc tính.
- Có 2 constructor, một constructor không có tham số, và một constructor với hai tham số cho hai thuộc tính của lớp
- Các thành phần của lớp có thể được lớp khác thừa kế.
Note: - Phương thức final thì không được được thừa kế, và phương thức có từ khóa static củng vậy.
2. Class B extends class A
- Class B có thêm thuộc tính: int SDT;
- Class B có override method input(); and showData(); trong đó sử dụng thêm properties int SDT;
Class A
package a;
import java.util.ArrayList;
import java.util.Scanner;
public class A {
private String tenNV;
private String diaChi;
Scanner input = new Scanner(System.in);
public A(){
}
public A(String tenNV, String diaChi){
this.tenNV = tenNV;
this.diaChi = diaChi;
}
public String getTenNV() {
return tenNV;
}
public void setTenNV(String tenNV) {
this.tenNV = tenNV;
}
public String getDiaChi() {
return diaChi;
}
public void setDiaChi(String diaChi) {
this.diaChi = diaChi;
}
public ArrayList<A> input(){
ArrayList<A> alA = new ArrayList<A>();
System.out.println("tenNV:");
this.tenNV = input.nextLine();
System.out.println("diaChi:");
this.diaChi = input.nextLine();
A a = new A(tenNV, diaChi);
alA.add(a);
return alA;
}
public void showData(ArrayList<A> alA){
for(A a :alA){
System.out.println(a.toString());
}
}
public String toString(){
return "tenNV" + this.tenNV + " diaChi: " + this.diaChi;
}
}
Class B
package a;
import java.util.ArrayList;
public class B extends A {
private int SDT;
public int getSDT() {
return SDT;
}
public void setSDT(int sDT) {
SDT = sDT;
}
/**
*
*/
public B() {
}
/**
* @param sDT
*/
public B(String tenNV, String diaChi,int sDT) {
//lấy lại 2 thuộc tính của class cha để gán cho class B
super(tenNV, diaChi);
this.SDT = sDT;
}
public ArrayList<A> input(){
//gọi lại method input của class cha
super.input();
System.out.println("SDT: ");
int SDT = Integer.parseInt(input.nextLine());
B b = new B(getTenNV(), getDiaChi(), SDT);
ArrayList<A> alA = new ArrayList<A>();
alA.add(b);
return alA;
}
@Override
public String toString(){
return super.toString() + " SDT: " + this.SDT;
}
public void showData(ArrayList<A> alA){
// in ra arrayList alA có kiểu dữ liệu A, đối tượng a của lớp A
for(A a :alA){
System.out.println(a.toString());
}
}
public static void main(String[] args) {
B b = new B();
ArrayList<A> alb = new ArrayList<A>();
b.showData(b.input());
}
}
Using the Keyword super
Accessing Superclass Members
If your method overrides one of its superclass's methods,
you can invoke the overridden method through the use of the keyword super.
You can also use super to
refer to a hidden field (although hiding fields is discouraged). Consider this
class, Superclass:
public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
Here is a subclass, called Subclass,
that overrides printMethod():
public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
Within Subclass,
the simple name printMethod() refers
to the one declared in Subclass,
which overrides the one in Superclass.
So, to refer to printMethod() inherited
fromSuperclass, Subclass must
use a qualified name, using super as
shown. Compiling and executing Subclass prints
the following:
Printed in Superclass.
Printed in Subclass
If your method overrides one of its superclass's methods,
you can invoke the overridden method through the use of the keyword
super.
You can also use super to
refer to a hidden field (although hiding fields is discouraged). Consider this
class, Superclass:public class Superclass {
public void printMethod() {
System.out.println("Printed in Superclass.");
}
}
Here is a subclass, called
Subclass,
that overrides printMethod():public class Subclass extends Superclass {
// overrides printMethod in Superclass
public void printMethod() {
super.printMethod();
System.out.println("Printed in Subclass");
}
public static void main(String[] args) {
Subclass s = new Subclass();
s.printMethod();
}
}
Within
Subclass,
the simple name printMethod() refers
to the one declared in Subclass,
which overrides the one in Superclass.
So, to refer to printMethod() inherited
fromSuperclass, Subclass must
use a qualified name, using super as
shown. Compiling and executing Subclass prints
the following:Printed in Superclass. Printed in Subclass
Subclass Constructors
The following example illustrates how to use the super keyword
to invoke a superclass's constructor. Recall from the Bicycle example
that MountainBike is
a subclass of Bicycle.
Here is the MountainBike (subclass)
constructor that calls the superclass constructor and then adds initialization
code of its own:
public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
Invocation of a superclass constructor must be the first
line in the subclass constructor.
The syntax for calling a superclass constructor
is
super();
or:
super(parameter list);
With super(),
the superclass no-argument constructor is called. With super(parameter
list), the superclass constructor with a matching parameter list is
called.
Note: If a constructor does not
explicitly invoke a superclass constructor, the Java compiler automatically
inserts a call to the no-argument constructor of the superclass. If the super
class does not have a no-argument constructor, you will get a compile-time
error. Object does have
such a constructor, so if Object is
the only superclass, there is no problem.
If a subclass constructor invokes a constructor of its
superclass, either explicitly or implicitly, you might think that there will be
a whole chain of constructors called, all the way back to the constructor
of Object.
In fact, this is the case. It is called constructor chaining, and you
need to be aware of it when there is a long line of class descent.
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
The following example illustrates how to use the
super keyword
to invoke a superclass's constructor. Recall from the Bicycle example
that MountainBike is
a subclass of Bicycle.
Here is the MountainBike (subclass)
constructor that calls the superclass constructor and then adds initialization
code of its own:public MountainBike(int startHeight,
int startCadence,
int startSpeed,
int startGear) {
super(startCadence, startSpeed, startGear);
seatHeight = startHeight;
}
Invocation of a superclass constructor must be the first
line in the subclass constructor.
The syntax for calling a superclass constructor
is
super();
or:
super(parameter list);
With
super(),
the superclass no-argument constructor is called. With super(parameter
list), the superclass constructor with a matching parameter list is
called.Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass. If the super class does not have a no-argument constructor, you will get a compile-time error.
Object does have
such a constructor, so if Object is
the only superclass, there is no problem.
If a subclass constructor invokes a constructor of its
superclass, either explicitly or implicitly, you might think that there will be
a whole chain of constructors called, all the way back to the constructor
of
Object.
In fact, this is the case. It is called constructor chaining, and you
need to be aware of it when there is a long line of class descent.
In
OOP,
OOP override
Method Overriding
Child class has the same method as of base class. In such cases child class overrides the parent class method without even touching the source code of the base class. This feature is known as method overriding.
Example:
public class BaseClass { public void methodToOverride() //Base class method { System.out.println ("I'm the method of BaseClass"); } } public class DerivedClass extends BaseClass { public void methodToOverride() //Derived Class method { System.out.println ("I'm the method of DerivedClass"); } } public class TestMethod { public static void main (String args []) { // BaseClass reference and object BaseClass obj1 = new BaseClass(); // BaseClass reference but DerivedClass object BaseClass obj2 = new DerivedClass(); // Calls the method from BaseClass class obj1.methodToOverride(); //Calls the method from DerivedClass class obj2.methodToOverride(); } }
I'm the method of BaseClass I'm the method of DerivedClass
Rules for Method Overriding:
1.applies only to inherited methods
2.object type (NOT reference variable type) determines which overridden method will be used at runtime
3.Overriding method can have different return type (refer this)
4.Overriding method must not have more restrictive access modifier
5.Abstract methods must be overridden
6.Static and final methods cannot be overridden
7.Constructors cannot be overridden
8.It is also known as Runtime polymorphism.
Super keyword in Overriding:
When invoking a superclass version of an overridden method the super keyword is used.
Example:
public class BaseClass { public void methodToOverride() //Base class method { System.out.println ("I'm the method of BaseClass"); } } public class DerivedClass extends BaseClass { public void methodToOverride() //Derived Class method { System.out.println ("I'm the method of DerivedClass"); } } public class TestMethod { public static void main (String args []) { // BaseClass reference and object BaseClass obj1 = new BaseClass(); // BaseClass reference but DerivedClass object BaseClass obj2 = new DerivedClass(); // Calls the method from BaseClass class obj1.methodToOverride(); //Calls the method from DerivedClass class obj2.methodToOverride(); } }
Output:
I'm the method of BaseClass I'm the method of DerivedClass
Tình hình là hôm nay nó đi thi về, điểm cao thôi rồi luôn, 4 điểm :)) .
Mà để có được 4 điểm đó thì nó đã bỏ ra rất nhiều công sức, học rất chăm chỉ với cả đầu tư một cơ số tiền đi Molly Coffe học bài nữa.
Học chăm vậy nên mấy project các năm trước nó làm rất ngon như là Tiểu lý phi đao đi một đường kiếm chết trăm con ruồi vậy. Đến lúc đi thi nó rất là oai hùng và phấn khích, như là chiến binh Spartacus sẽ đánh tan mọi quân thù.
Những cuộc sống không như nó nghĩ, nó đã tử trận dưới cái đề mà mỗi tạo cái database và làm mấy cái constructor thì đã gần mất cha hơn một tiếng rồi, lại còn thêm cái add dữ liệu vào nữa chứ, có tận mấy bảng mà toàn khóa nội khóa ngoại, add thế thì chỉ có thằng nào chạy nhanh như Usain Bolt thì may ra làm kịp. Nhưng mà không sao, nó đã hi sinh một cách ngoan cường, sau trận chiến này, nó đã có một đống kiến thức trong đầu. Đó sẽ là bạn đạp để nó bật lên mạnh mẽ.
Kết thúc tất cả các môn học rồi, chỉ còn thực tập tốt nghiệp và đồ án nữa là nó sẽ trở thành Kỹ sư!
Bắt đầu từ hôm nay nó sẽ đầu tư Coding và English ngày 13 tiếng, còn lại làm những việc yêu thích. Sau năm nay nó sẽ lên một tầm cao mới, akkakakakkak :D :D
Lên kế hoạch chinh phục một ngày, rồi một tuần, một tháng, một năm là nó sẽ có một cuộc đời trôi qua và để lại những điều gì đó tốt đẹp cho cuộc sống này thôi.

I decide my life..................... :D :D