0
Introduction to         Java Programming                Y. Daniel LiangEdited by Hoàng Văn Hậu – VTC Academy – THSoft co.,...
Introduction Course Objectives Organization of the BookVTC Academy       THSoft Co.,Ltd   2
Course Objectives   Upon completing the course, you will understand    –   Create, compile, and run Java programs    –   ...
Course Objectives, cont. You         will be able to    – Develop programs using Eclipse IDE    – Write simple programs u...
Session 03: Method and Class Methods Object-Oriented   Programming Classes Packages Subclassingand Inheritance Polym...
Introducing Methods                      Method StructureA method is acollection ofstatements that aregrouped togetherto p...
Introducing Methods, cont.•parameter profile refers to the type, order, andnumber of the parameters of a method.•method si...
Declaring Methodspublic static int max(int num1,  int num2) {   if (num1 > num2)     return num1;   else     return num2;}...
Calling Methods, cont.                                                                       pass i                       ...
Calling Methods, cont.The main method     pass 5     The max method  i:          5                   num1:         5      ...
CAUTIONA return statement is required for a nonvoidmethod. The following method is logicallycorrect, but it has a compilat...
Actions on Eclipse   Open Eclipse IDE    –   Create project: Session3Ex    –   Create package: com.vtcacademy.exopp    – ...
The Math Class Class       constants:    – PI    –E Class       methods:    – Trigonometric Methods    – Exponent Method...
Trigonometric Methods sin(double        a) cos(double        a) tan(double        a) acos(double        a) asin(doubl...
Exponent Methods   exp(double a)    Returns e raised to the power of a.   log(double a)    Returns the natural logarithm...
Rounding Methods   double ceil(double x)    x rounded up to its nearest integer. This integer is returned as a     double...
min, max, abs, and random max(a,      b)and min(a, b)   Returns the maximum or minimum of two   parameters. abs(a)   Ret...
Example 3.1 Computing Mean       and Standard DeviationGenerate n random numbers and compute the mean and standard deviati...
Example 3.2 Obtaining Random             CharactersWrite the methods for generating randomcharacters. The program uses the...
OO Programming ConceptsAn object                                       A Circle object                                    ...
Class and Objects                        Circle                   UML Graphical notation for classes                  radi...
Class Declarationclass Circle {  double radius = 1.0;    double findArea(){      return radius * radius * 3.14159;    }}  ...
Declaring Object Reference Variables  ClassName objectReference;  Example:  Circle myCircle;VTC Academy     THSoft Co.,Ltd...
Creating ObjectsobjectReference = new ClassName();Example:myCircle = new Circle();The object reference is assigned to the ...
Declaring/Creating Objects               in a Single StepClassName objectReference = new ClassName();Example:Circle myCirc...
Constructors  Circle(double r) {    radius = r;  }                Constructors are a                   special kind of  Ci...
Constructors  Circle(double r) {    radius = r;  }                Constructors are a                   special kind of  Ci...
Constructors, cont.A constructor with no parameters is referred toas a default constructor.     Constructors must have the...
Example 3.3 Using Classes from       the Java Library Objective:    Demonstrate using classes from the   Java library. Us...
Subclassing and Inheritance private None protected Public                                  Illustration on codeVTC Aca...
Example 3.4                                  Shape    TwoDimensionalShape                            ThreeDimensionalShape...
Example 3.4 http://blogs.unsw.edu.au/comp1400/blog/20   11/09/tut-10/VTC Academy        THSoft Co.,Ltd         32
Abstract Classes and                    Methods Abstract      classes    – Are superclasses (called abstract superclasses...
Abstract Classes and Methods               (Cont.) Abstract classes not required, but reduce  client code dependencies T...
Abstract Classes and Methods               (Cont.)   Application example     – Abstract class Shape             Declares...
Case Study: Creating and Using            Interfaces   Use interface Shape    – Replace abstract class Shape   Interface...
1   // Fig. 10.18: Shape.java  2   // Shape interface declaration.  3  4   public interface Shape {  5     public double g...
1    // Fig. 10.19: Point.java      2    // Point class declaration implements interface Shape.      3      4    public cl...
Action on class Teacher    – hauc2@yahoo.com    – 0984380003    – https://play.google.com/store/search?q=thsoft+co&c=apps...
Upcoming SlideShare
Loading in...5
×

Java cơ bản java co ban

306

Published on

Java cơ bản, b

Published in: Technology, News & Politics
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total Views
306
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
5
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide

Transcript of "Java cơ bản java co ban "

  1. 1. Introduction to Java Programming Y. Daniel LiangEdited by Hoàng Văn Hậu – VTC Academy – THSoft co.,ltd https://play.google.com/store/apps/developer?id=THSoft+Co.,Ltd
  2. 2. Introduction Course Objectives Organization of the BookVTC Academy THSoft Co.,Ltd 2
  3. 3. Course Objectives Upon completing the course, you will understand – Create, compile, and run Java programs – Primitive data types – Java control flow – Methods – Arrays (for teaching Java in two semesters, this could be the end) – Object-oriented programming – Core Java classes (Swing, exception, internationalization, multithreading, multimedia, I/O, networking, Java Collections Framework)VTC Academy THSoft Co.,Ltd 3
  4. 4. Course Objectives, cont. You will be able to – Develop programs using Eclipse IDE – Write simple programs using primitive data types, control statements, methods, and arrays. – Create and use methods – Write interesting projectsVTC Academy THSoft Co.,Ltd 4
  5. 5. Session 03: Method and Class Methods Object-Oriented Programming Classes Packages Subclassingand Inheritance PolymorphismVTC Academy THSoft Co.,Ltd 5
  6. 6. Introducing Methods Method StructureA method is acollection ofstatements that aregrouped togetherto perform anoperation. VTC Academy THSoft Co.,Ltd 6
  7. 7. Introducing Methods, cont.•parameter profile refers to the type, order, andnumber of the parameters of a method.•method signature is the combination of themethod name and the parameter profiles.•The parameters defined in the method headerare known as formal parameters.•When a method is invoked, its formalparameters are replaced by variables or data,which are referred to as actual parameters. VTC Academy THSoft Co.,Ltd 7
  8. 8. Declaring Methodspublic static int max(int num1, int num2) { if (num1 > num2) return num1; else return num2;} VTC Academy THSoft Co.,Ltd 8
  9. 9. Calling Methods, cont. pass i pass jpublic static void main(String[] args) { public static int max(int num1, int num2) { int i = 5; int result; int j = 2; int k = max(i, j); if (num1 > num2) result = num1; System.out.println( else "The maximum between " + i + result = num2; " and " + j + " is " + k);} return result; } VTC Academy THSoft Co.,Ltd 9
  10. 10. Calling Methods, cont.The main method pass 5 The max method i: 5 num1: 5 pass 2 parameters j: 2 num2: 2 k: 5 result: 5VTC Academy THSoft Co.,Ltd 10
  11. 11. CAUTIONA return statement is required for a nonvoidmethod. The following method is logicallycorrect, but it has a compilation error, because theJava compiler thinks it possible that this methoddoes not return any value. public static int xMethod(int n) { if (n > 0) return 1; else if (n == 0) return 0; else if (n < 0) return –1; }To fix this problem, delete if (n<0) in the code. VTC Academy THSoft Co.,Ltd 11
  12. 12. Actions on Eclipse Open Eclipse IDE – Create project: Session3Ex – Create package: com.vtcacademy.exopp – Create java class: Ex3WithOpp.java (with main method) – Create java class: Circle.java Source RunVTC Academy THSoft Co.,Ltd 12
  13. 13. The Math Class Class constants: – PI –E Class methods: – Trigonometric Methods – Exponent Methods – Rounding Methods – min, max, abs, and random MethodsVTC Academy THSoft Co.,Ltd 13
  14. 14. Trigonometric Methods sin(double a) cos(double a) tan(double a) acos(double a) asin(double a) atan(double a)VTC Academy THSoft Co.,Ltd 14
  15. 15. Exponent Methods exp(double a) Returns e raised to the power of a. log(double a) Returns the natural logarithm of a. pow(double a, double b) Returns a raised to the power of b. sqrt(double a) Returns the square root of a.VTC Academy THSoft Co.,Ltd 15
  16. 16. Rounding Methods double ceil(double x) x rounded up to its nearest integer. This integer is returned as a double value. double floor(double x) x is rounded down to its nearest integer. This integer is returned as a double value. double rint(double x) x is rounded to its nearest integer. If x is equally close to two integers, the even one is returned as a double. int round(float x) Return (int)Math.floor(x+0.5). long round(double x) Return (long)Math.floor(x+0.5).VTC Academy THSoft Co.,Ltd 16
  17. 17. min, max, abs, and random max(a, b)and min(a, b) Returns the maximum or minimum of two parameters. abs(a) Returns the absolute value of the parameter. random() Returns a random double value in the range [0.0, 1.0).VTC Academy THSoft Co.,Ltd 17
  18. 18. Example 3.1 Computing Mean and Standard DeviationGenerate n random numbers and compute the mean and standard deviation n n xi n ( xi )2 i 1 xi2 i 1 mean i 1 n n deviation n 1 VTC Academy THSoft Co.,Ltd 18
  19. 19. Example 3.2 Obtaining Random CharactersWrite the methods for generating randomcharacters. The program uses these methods togenerate 175 random characters between „! and „~and displays 25 characters per line. To find out thecharacters between „! and „~, see Appendix B,“The ASCII Character Set.” VTC Academy THSoft Co.,Ltd 19
  20. 20. OO Programming ConceptsAn object A Circle object Data Field data field 1 radius = 5 ... State Method data field n findArea method 1 ... Behavior method n VTC Academy THSoft Co.,Ltd 20
  21. 21. Class and Objects Circle UML Graphical notation for classes radius: double UML Graphical notation for fields UML Graphical notation for methods findArea(): doublenew Circle() new Circle() circle1: Circle circlen: Circle UML Graphical notation for objects radius = 2 ... radius = 5 Illustration on code VTC Academy THSoft Co.,Ltd 21
  22. 22. Class Declarationclass Circle { double radius = 1.0; double findArea(){ return radius * radius * 3.14159; }} VTC Academy THSoft Co.,Ltd 22
  23. 23. Declaring Object Reference Variables ClassName objectReference; Example: Circle myCircle;VTC Academy THSoft Co.,Ltd 23
  24. 24. Creating ObjectsobjectReference = new ClassName();Example:myCircle = new Circle();The object reference is assigned to the object reference variable.VTC Academy THSoft Co.,Ltd 24
  25. 25. Declaring/Creating Objects in a Single StepClassName objectReference = new ClassName();Example:Circle myCircle = new Circle();Circle myCircle2; VTC Academy THSoft Co.,Ltd 25
  26. 26. Constructors Circle(double r) { radius = r; } Constructors are a special kind of Circle() { methods that are radius = 1.0; invoked to construct } objects. myCircle = new Circle(5.0);VTC Academy THSoft Co.,Ltd 26
  27. 27. Constructors Circle(double r) { radius = r; } Constructors are a special kind of Circle() { methods that are radius = 1.0; invoked to construct } objects. myCircle = new Circle(5.0);VTC Academy THSoft Co.,Ltd 27
  28. 28. Constructors, cont.A constructor with no parameters is referred toas a default constructor. Constructors must have the same nameas the class itself. Constructors do not have a return type—not even void. Constructors are invoked using the newoperator when an object is created.Constructors play the role of initializingobjects. VTC Academy THSoft Co.,Ltd 28
  29. 29. Example 3.3 Using Classes from the Java Library Objective: Demonstrate using classes from the Java library. Use the JFrame class in the javax.swing package to create two frames; use the methods in the JFrame class to set the title, size and location of the frames and to display the frames. Illustration on codeVTC Academy THSoft Co.,Ltd 29
  30. 30. Subclassing and Inheritance private None protected Public Illustration on codeVTC Academy THSoft Co.,Ltd 30
  31. 31. Example 3.4 Shape TwoDimensionalShape ThreeDimensionalShapeCircle Square Triangle Sphere Cube TetrahedronVTC Academy THSoft Co.,Ltd 31
  32. 32. Example 3.4 http://blogs.unsw.edu.au/comp1400/blog/20 11/09/tut-10/VTC Academy THSoft Co.,Ltd 32
  33. 33. Abstract Classes and Methods Abstract classes – Are superclasses (called abstract superclasses) – Cannot be instantiated – Incomplete  subclasses fill in "missing pieces" Concrete classes – Can be instantiated – Implement every method they declare – Provide specificsVTC Academy THSoft Co.,Ltd 33
  34. 34. Abstract Classes and Methods (Cont.) Abstract classes not required, but reduce client code dependencies To make a class abstract – Declare with keyword abstract – Contain one or more abstract methods public abstract void draw(); – Abstract methods  No implementation, must be overriddenVTC Academy THSoft Co.,Ltd 34
  35. 35. Abstract Classes and Methods (Cont.) Application example – Abstract class Shape  Declares draw as abstract method – Circle, Triangle, Rectangle extends Shape  Each must implement draw – Each object can draw itself Iterators – Array, ArrayList (Chapter 22) – Walk through list elements – Used in polymorphic programming to traverse a collection Illustration on codeVTC Academy THSoft Co.,Ltd 35
  36. 36. Case Study: Creating and Using Interfaces Use interface Shape – Replace abstract class Shape Interface – Declaration begins with interface keyword – Classes implement an interface (and its methods) – Contains public abstract methods  Classes (that implement the interface) must implement these methodsVTC Academy THSoft Co.,Ltd 36
  37. 37. 1 // Fig. 10.18: Shape.java 2 // Shape interface declaration. 3 4 public interface Shape { 5 public double getArea(); // calculate area 6 public double getVolume(); // calculate volume 7 public String getName(); // return shape name 8 9 } // end interface Shape Lines 5-7 Classes that implement Shape must implement these methodsVTC Academy THSoft Co.,Ltd 37
  38. 38. 1 // Fig. 10.19: Point.java 2 // Point class declaration implements interface Shape. 3 4 public class Point extends Object implements Shape { 5 private int x; // x part of coordinate pair 6 private int y; // y part of coordinate pair 7 8 // no-argument constructor; x and y default to 0 9 public Point() 10 { 11 // implicit call to Object constructor occurs here 12 } 13 14 // constructor 15 public Point( int xValue, int yValue ) 16 { Error compile 17 // implicit call to Object constructor occurs here 18 x = xValue; // no need for validation 19 y = yValue; // no need for validation 20 } 21 22 // set x in coordinate pair 23 public void setX( int xValue ) 24 { 25 x = xValue; // no need for validation 26 } 27VTC Academy THSoft Co.,Ltd 38
  39. 39. Action on class Teacher – hauc2@yahoo.com – 0984380003 – https://play.google.com/store/search?q=thsoft+co&c=apps Captions MembersVTC Academy THSoft Co.,Ltd 39
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×