100 likes | 237 Views
การโปรแกรมเชิงวัตถุด้วยภาษา JAVA. Object-Oriented Programming. มหาวิทยาลัยเนชั่น http:// www. nation. ac.th. บุรินทร์ รุจจนพันธุ์ . ปรับปรุง 24 สิงหาคม 2550. โปรแกรมภาษาจาวา. class human { public static void main (String args[]) { System.out.println(“wow”); } }.
E N D
การโปรแกรมเชิงวัตถุด้วยภาษา JAVA Object-Oriented Programming มหาวิทยาลัยเนชั่น http://www.nation.ac.th บุรินทร์ รุจจนพันธุ์ . ปรับปรุง 24 สิงหาคม 2550
โปรแกรมภาษาจาวา class human { public static void main (String args[]) { System.out.println(“wow”); } }
หลักพื้นฐานของ OO in Java 1. Inheritance 2. Encapsulation 3. Polymorphism 3.1 Overloading 3.2 Overriding
Inheritance class father { void homeaddr(){System.out.println(“lp”);} } class child extends father { public static void main (String args[]) { homeaddr(); } }
Encapsulation class friend { private int val; public int getter(){ return this.val;} public void setter(int a){ this.val=a;} } class child { public static void main (String args[]) { friend x = new friend(); x.setter(5); System.out.println(x.getter()); } }
Polymorphism : Overloading overloaded methods: - appear in the same class or a subclass - have the same name but, - have different parameter lists, and, - can have different return type
Polymorphism : Overloading class child { static int bag(){ return 1; } static int bag(int a){ return a; } static int bag(String a){ return a.length(); } public static void main (String args[]) { System.out.println(bag()); System.out.println(bag(5)); System.out.println(bag(“abc”)); } }
Polymorphism : Overriding overriding methods: - appear in subclasses have the same name as a superclass method - have the same parameter list as a superclass method - have the same return type as as a superclass method - the access modifier for the overriding method may not be more restrictive than the access modifier of the superclass method if the superclass method is public, the overriding method must be public if the superclass method is protected, the overriding method may be protected or public if the superclass method is package, the overriding method may be packagage, protected, or public if the superclass methods is private, it is not inherited and overriding is not an issue - the throws clause of the overriding method may only include exceptions that can be thrown by the superclass method, including it's subclasses
Polymorphism : Overriding (1/2) class father { static void addr(){System.out.println(“lp”);} } class child extends father { static void addr(){System.out.println(“cm”);} public static void main (String args[]) { addr(); new father().addr(); } }
Polymorphism : Overriding (2/2) class father { void addr(){System.out.println(“lp”);} } class child extends father { void addr(){System.out.println(“cm”);} public static void main (String args[]) { child c = new child(); c.addr(); } }