Lec 15
Lec 15
Lecture # 15
Example: Result:
2
Static vs. Non-Static
• Java programs that have either static or public attributes and methods.
Example: Result:
3
Static vs. Non-Static
• Java programs that have either static or public attributes and methods.
Example: Result:
4
Access Methods with an Object
• Create a Car object named myCar. Call the fullThrottle() and speed() methods on
the myCar object, and run the program:
Example: Result:
5
Using Multiple Classes
• It is a good practice to create an object of a class and access it in another class.
Main.java
Second.java
Result:
6
Java Constructors
• A constructor in Java is a special method that is used to initialize objects.
• The constructor is called when an object of a class is created.
• It can be used to set initial values for object attributes:
Example: Result:
7
Constructor Parameters
• Constructors can also take parameters, which is used to initialize attributes.
• The following example adds an int y parameter to the constructor.
• Inside the constructor we set x to y (x=y).
• When we call the constructor, we pass a parameter to the constructor (5), which will
set the value of x to 5:
Example: Result:
8
Constructor Parameters
• You can have as many parameters as you want:
Example: Result:
9
THANK YOU!