Professional Documents
Culture Documents
Name: Date:
Grade/Section: Rating:
Teacher:
Example
Create a constructor:
// Outputs 5
ARELLANO UNIVERSITY – PLARIDEL CAMPUS
53 General Kalentong St. Mandaluyong
Senior High School
Dynamic Learning Program
Note that the constructor name must match the class name, and it cannot have
a return type (like void).
Also note that the constructor is called when the object is created.
Constructor Parameters
The following example adds an int year, and String name parameter to the
constructor. Inside the constructor we set year = 1969, and name = “Mustang”).
When we call the constructor, we pass a parameter to the constructor (year and
name), which will output 1969 Mustang.
Example
public class Main {
int modelYear;
String modelName;
Methods are declared within a class, and that they are used to perform certain
actions
You will often see Java programs that have either static or public attributes and
methods.
ARELLANO UNIVERSITY – PLARIDEL CAMPUS
53 General Kalentong St. Mandaluyong
Senior High School
Dynamic Learning Program
// Public method
public void myPublicMethod() {
// Main method
public static void main(String[] args) {
myStaticMethod(); // Call the static method
// myPublicMethod(); This would compile an error
Create a Car object named myCar. Call the fullThrottle() and speed() methods on
the myCar object, and run the program:
ARELLANO UNIVERSITY – PLARIDEL CAMPUS
53 General Kalentong St. Mandaluyong
Senior High School
Dynamic Learning Program
Remember that the name of the java file should match the class name. In this
example, we have created two files in the same directory:
Main.java
Second.java
ARELLANO UNIVERSITY – PLARIDEL CAMPUS
53 General Kalentong St. Mandaluyong
Senior High School
Dynamic Learning Program
Main.java
Second.java
class Second {
NOTE:
The dot (.) is used to access the object's attributes and methods.
QUESTIONS/ACTIVITY QUESTIONS:
1. What method can be access without creating an object of the class? Static
method
2. What method can only be access by objects? Non static Method
3. What is a special method that is used to initialize objects? Constructor
4. Where do we declare methods? Class
5. What method will be get executed first? static
ARELLANO UNIVERSITY – PLARIDEL CAMPUS
53 General Kalentong St. Mandaluyong
Senior High School
Dynamic Learning Program