- Hands-On Automation Testing with Java for Beginners
- Rahul Shetty
- 352字
- 2021-07-23 16:26:33
Accessing an object in Java
To access the method of the class, we write the object name and then . (dot). All the methods that qualify for the class are displayed in a drop-down—this is another great feature in Eclipse. We can just look for the method in the drop-down rather than searching for it through the code.
In the example, we are using the getData() method. The rest of the methods shown are all built-in Java methods. Observe how the methods are displayed:
On clicking on getData(), the getData() block will be transferred to the line where the object was called, and when we run the program, the code will be executed as it is part of the main block. The accessing code will finally look like this:
fn.getData();
Let's see what the final code for this example will look like:
package coreJavaTraining;
public class Firstclass {
public void getData()
{
System.out.println(" I am in method")
}
public static void main(String[] args)
{
Firstclass fn=new Firstclass();
fn.getData();
System.out.println("hi");
System.out.println("hello world");
}
}
So if we run the class given in the example, our result will be as follows:
I am in method is what we see in the output; this is because control starts from the memory-allocation line, creates an object, and using the object we call the method of that class. Control goes back to the getData() block and completes the lines of code that are present in that particular block; it executes the print statement, and we see that it gets printed. This is why objects are powerful in calling a method.
The same technique can be used for calling integers. Let's say we declare a variable in the a class and assign a value to it. We can print the variable value by adding the following line in the main method:
System.out.println(fn.a);
This is one way of using classes, objects, and methods in Java; basically we are encapsulating.
- Vue.js 3.x快速入門
- Python快樂編程:人工智能深度學習基礎
- ThinkPHP 5實戰
- Docker技術入門與實戰(第3版)
- 區塊鏈架構與實現:Cosmos詳解
- JavaScript 網頁編程從入門到精通 (清華社"視頻大講堂"大系·網絡開發視頻大講堂)
- Mastering Scientific Computing with R
- Elasticsearch for Hadoop
- ASP.NET程序設計教程
- C++面向對象程序設計習題解答與上機指導(第三版)
- 深入淺出React和Redux
- Cocos2d-x Game Development Blueprints
- Learning JavaScript Data Structures and Algorithms(Second Edition)
- Learning Nessus for Penetration Testing
- 超簡單:用Python讓Excel飛起來(實戰150例)