This document discusses Java classes, objects, and constructors. It explains that a class contains instance variables and methods, and defines common behaviors for objects. An object is instantiated from a class using the new reserved word and can then access the class's instance variables and methods. The document provides an example of creating a Java class with an instance variable and method to demonstrate how objects are made from classes and can then access class members.
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. Common example of methods
• main()
• System.out.println();
• JOptionPane.showMessageDialog();
• String str = JOptionPane.showInputDialog();
• Int y = Integer.parseInt(str);
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. 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. 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()
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
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