Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Java lec class, objects and constructors

2,241 views

Published on

JAVA

Published in: Education, Technology
  • Be the first to comment

Java lec class, objects and constructors

  1. 1. JAVA CLASSES, OBJECTS AND CONSTRUCTORS JAVA LECTURE BY: LJRABOY
  2. 2. Object-Oriented Approach • Class – Instance variables – attributes of an object – Methods – functions that manipulates objects • Are subprograms • Divide-and-conquer model • One large programs – subdivide the program into smaller subprograms • Process needed in the program • Methods are usually named using a action words such as computeSum(), setValueOfX(), getValueOfY() and etc – A user-defined method can be used after the declaration of main() as a static method. – Static method – does not need an object to access its methods and instance variables.
  3. 3. Common example of methods • main() • System.out.println(); • JOptionPane.showMessageDialog(); • String str = JOptionPane.showInputDialog(); • Int y = Integer.parseInt(str);
  4. 4. The Class • The class contains both the variables and its methods • Class is represented by its own filename • example of a declaration: public class MyClass{ public static void main(String args *[]) { } }
  5. 5. The Class (cont) • Is a general category of an object • it contains the very common behavior of an object. • A class does not necessarily needs main() because a class can be used in terms of using objects. Together with its instance variables and instance methods.
  6. 6. The Object • Instantiate an object using a new reserved word. • So all the instance variables and instance methods of the class can now be accessed by an objects. • This instance variables and methods can be accessed using the dot “.” operator. ObjectName.instance_Variable ObjectName.instance_method()
  7. 7. Getting Started • Creating a class – Instance variables – Instance methods
  8. 8. Example: • Start with creating a new Java Basic Application • Name your class: – Example: MyClassMain – Select File, New  File
  9. 9. Select Java Class
  10. 10. Provide another filename for your class
  11. 11. Two files for the project
  12. 12. Inside MyClassMain class
  13. 13. Inside MyOwnClass class • Public  access modifier , can be accessed anywhere in the package • Reserved word class • MyOwnClass  User- defined class name • public MyOwnClass(){ }  constructor Constructor – used for initialization
  14. 14. Modifying MyOwnClass
  15. 15. MyClassMain class
  16. 16. Format of using a method public return_type methodname(parameters) { // body of the method } Where: public is an access modifier Return_type – any primitive type/class type Methodname – user-defined method name Parameters – optional, values to be passed to the method

×