- 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.
- C++ Primer習題集(第5版)
- Debian 7:System Administration Best Practices
- 軟件測試項目實戰之性能測試篇
- 精通Scrapy網絡爬蟲
- Java編程技術與項目實戰(第2版)
- Visual FoxPro程序設計習題集及實驗指導(第四版)
- INSTANT Sinatra Starter
- SQL Server數據庫管理與開發兵書
- Java程序設計案例教程
- 大話Java:程序設計從入門到精通
- Getting Started with Nano Server
- .NET Standard 2.0 Cookbook
- Image Processing with ImageJ
- Java程序設計與項目案例教程
- Spring 5 Design Patterns