I've been doing Java for three months in newcomer training, but the language used in my department was Visual Basic .NET, so I had to learn anew. However, I wonder if there are not so many cases of "migrating from Java to VB.NET" (C # is normal now ...?), I could not find a site that details grammar comparison etc. did.
--Understanding Java writing and programming concepts ――I want to be able to write programs in VB.NET from now on
I'll provide a reference for comparing Java and VB.NET to those who say (well, I'm in sync with a few people).
That said, there should be almost no code that depends on the environment.
--Visual Basic .NET (VB.NET) is simply referred to as "VB" below. --The Java and VB code in the same section basically do the same thing.
--Hiroshi Hayama "Basic Visual Basic 2019" (Impress Corporation, 2019) ――A textbook that is helpful in learning VB. If you know other languages such as Java, you can read it in full time x 1 week. -[To become a VB.net programmer from a Java shop --Qiita](https://qiita.com/5zm/items/44d05463875ff0e29da0#3-%E3%82%B5%E3%83%B3%E3%83 % 97% E3% 83% AB) --A few articles that look at VB from a Java perspective. --Visual Basic documentation--Introduction, tutorials, references. | Microsoft Docs
main
Main.java
public class Main {
public static void main(String[] args) {
System.out.println("Hello Java!");
int a; String b; double c;
}
}
--Blocks are separated by {}
--Modifiers such as public
are lowercase
--End the sentence with ;
(line feed itself has no meaning)
Form1.vb
Public Class Form1
Private Sub ShowMessage(sender As Object, e As EventArgs) _
Handles Button1.Click
Console.WriteLine("Hello VB!")
Dim a As Integer : Dim b As String : Dim c As Double
End Sub
End Class
--Blocks are divided as (qualifier) Class
~ ʻEnd Class --The end of the line is the end of the statement. --If you want to intentionally break a line in a long sentence, insert the line continuation character
_. --However, from VB2010, it is possible to start a new line without a line continuation character under certain conditions (implicit line continuation). --Refer to [What's new in Visual Basic 2010-@IT](https://www.atmarkit.co.jp/fdotnet/chushin/vb2010features_01/vb2010features_01_01.html) for detailed rules. --If you want to put multiple statements in one line, separate them with
:`.
Comment.java
//Singular line comment
/*
*Multi-line comment
*/
Comment.vb
'Singular line comment
A person who can generate API documents with a dedicated tool and display explanations by mouse over the method name.
-** Java: ** Described in Javadoc format. / **
~ * /
--In Eclipse, you can generate by pressing Alt + Shift + J after hovering over the target member.
JavaDoc.java
/**
*Multiplies the two integers specified by the argument and returns the result.
* @param a Multiply number 1
* @param a number to multiply 2
* @result of return multiplication
*/
public static int doCalc(int a, int b) {
return a * b;
}
-** VB: ** Described in XML. '''`` --In Visual Studio, you can generate it by typing
'''` on the line just above the target member.
XmlDoc.vb
''' <summary>
'''Multiplies the two integers specified by the argument and returns the result.
''' </summary>
''' <param name="a">Number to multiply 1</param>
''' <param name="b">Number to multiply 2</param>
''' <returns>The result of multiplication</returns>
Public Shared Function DoCalc(a As Integer, b As Integer) As Integer
Return a * b
End Function
--Insert XML document comments --Visual Studio | Microsoft Docs
Main.class
(built Java bytecode)main.java
** (source code). Project
(Eclipse project file).settings
.classpath
VisualStudioSolution.sln
** (VS solution file)
FirstProject.vbproj
(VB project file)
FirstProject.exe
** (built debug executable)App.config
-** Form1.vb
** (source code [behavior])
-** Form1.Designer.vb
** (source code [design])Visual Studio allows you to combine multiple projects into a ** solution **. (Although there is also a ** working set ** in Eclipse)
byte
, short
, ʻint,
long,
float,
double,
char,
boolean) --Reference type (such as
String`)Byte
, Short
, ʻInteger,
Long, **
Single** (equivalent to float),
Double, **
Decimal** (decimal),
Char,
Boolean, **
Date**, etc.) --Reference type (such as
String`)Date types need to use standard APIs such as java.util.Date
, java.util.Calender
, and java.time
in Java (that is, they are inevitably reference types). However, in VB, [Date
type](https://docs.microsoft.com/ja-jp/dotnet/visual-basic/language-reference/data-types/date-data-type] that can manage date and time ) Is prepared as standard.
DeclareVariable.java
int number; // package private
String message; // package private
public int publicNumber;
private String privateMessage;
DeclareVariable.vb
Dim Something ' Private
Dim Number As Integer ' Private
Dim Message As String ' Private
Public PublicNumber As Integer
In VB standard settings, you can omit the type specification when declaring a variable. In that case, the data type of the variable is automatically determined according to the initial data type (type estimation). If there is no initial value, it is regarded as Object type. ʻOption Strict On` disables type estimation.
letter | Java | VB | Remarks |
---|---|---|---|
Half-width alphanumeric characters | ○ | ○ | |
Japanese characters | ○ | ○ | Of course not recommended |
_ |
○ | ○ | underscore |
& |
○ | × | |
Numbers at the beginning | × | × |
InitiarizeVariable.java
int number = 100;
String message = "Hello";
InitiarizeVariable.vb
Dim Number As Integer = 100
Dim Message As String = "Hello"
Dim Pi = 3.14 'Automatically treated as Double type
Dim BlankNumber As Integer 'The initial value automatically becomes "0"
Dim BlankMessage As String 'The initial value automatically becomes "Nothing"
Constant.java
final int MAX_STOCK = 100;
public static final String VERSION_ID = "v1.0.1-RELEASE";
Constant.vb
Const MAX_STOCK As Integer = 100
Const VERSION_ID As String = "v1.0.1-RELEASE" 'Shared cannot be used with Const statements
-Data Type Overview (Visual Basic) | Microsoft Docs
function | Java | VB.NET | Remarks |
---|---|---|---|
Addition | a + b |
a + b |
|
Subtraction | a - b |
a - b |
|
Multiply | a * b |
a * b |
|
division | a / b |
a / b |
|
Integer division (quotient) | N/A | a \ b |
[VB]Both a and b must be of integer type.23 \ 5 The result of4 become |
Surplus (remainder) | a % b |
a Mod b |
23 % 5 Or23 Mod 5 The result of3 become |
Exponentiation | (None as an operator) | a ^ b |
VB^ Note that is the highest priority of arithmetic operators |
Increment | ++a Ora++ |
N/A | In VBa += 1 There is no choice but to write |
Increment | --a Ora-- |
N/A | In VBa -= 1 There is no choice but to write |
In Java, if both the number to be divided ʻa and the number to be divided
bare integers, the result will be truncated to an integer. This does not change even if the assignment destination is a variable such as
double` type.
DivideInteger.java
double x;
x = 23 / 5; //x is 4.Become 0
If at least one is a decimal (double precision floating point), the result will also be a decimal.
java.DivideDouble.java
double x;
x = 23 / 5.0 //x is 4.Become 6
On the other hand, in VB, the calculation is performed so that the accuracy does not drop as much as possible.
DivideInteger.vb
Dim x As Double
x = 23 / 5 'x is 4 instead of 4.Become 6
Even in VB, if you want to divide integers like Java, use the \
operator.
DivideWithBackSlashOperator.
Dim x As Double
x = 23 \ 5 'x becomes 4
In Java, use java.lang.Math.pow (a, b)
.
The first argument ʻais the base and the second argument
b is the exponent (that is, ʻa ^ b
in VB).
function | Java | VB.NET | Remarks |
---|---|---|---|
Substitute as it is | a = b |
a = b |
|
Substitute the addition result | a += b |
a += b |
|
Substitute the subtraction result | a -= b |
a -= b |
|
Substitute the multiplication result | a *= b |
a *= b |
|
Substitute the division result | a /= b |
a /= b |
|
Substitute the result of integer division | N/A | a \= b |
|
Substitute the remainder (remainder) | a % b |
N/A | [VB]There is no mod compatible |
(Bitwise operation system omitted)
function | Java | VB.NET | Remarks |
---|---|---|---|
a is less than b | a < b |
a < b |
|
a is less than or equal to b | a <= b |
a <= b |
|
a is greater than b | a > b |
a > b |
|
a is more than b | a >= b |
a >= b |
|
a is equal to b | a == b |
a = b |
In VB= Is one |
a is not equal to b | a != b |
a <> b |
In the table below, ʻA and
B` represent conditional expressions (expressions that return True / False).
logic | function | Java | VB.NET |
---|---|---|---|
Logical AND(AND) | A and B | N/A | A And B |
Logical AND(AND) | A and B(Short-circuit evaluation) | A && B |
A AndAlso B |
Logical sum(OR) | A or B | N/A | A Or B |
Logical sum(OR) | A or B(Short-circuit evaluation) | A && B |
A OrElse B |
Logical AND(NOT) | Not A | !A |
Not A |
Exclusive OR(XOR) | A or B, but not A and B | ^A |
A Xor B |
** Short-circuit evaluation: ** If A is False, it is confirmed that the entire conditional expression is False, so proceed without evaluating B. At this time, even if some method is written in B, it will not be executed. You can use this to write an expression in B that will result in an error if A is not True. Example: ʻIf Integer.TryParse (str, num) AndAlso num <5 Then ... `
Java uses +
to concatenate strings, while VB uses &
.
It is possible to concatenate strings with +
in VB, but Microsoft recommends using &
because it may result in unintended results or errors if one is not a string type. ing.
-Operator | Introduction to Java Code --Operators --Visual Basic | Microsoft Docs
ConditionalBranch.java
if (age < 20) canBuyAlcohol = true;
if (age < 13) {
fareType = "child";
} else if (age < 18) {
fareType = "student";
} else {
fareType = "adult";
}
ConditionalBranch.vb
If age < 20 Then canBuyAlcohol = True 'If it's one line, you don't need End If
If age < 13 Then
FareType = "child"
ElseIf age < 18 Then
FareType = "student"
Else
FareType = "adult"
End If
In VB, it is also possible to write multiple statements on one line using ":
" as follows.
ConditionalBranchInOneLine.vb
If 20 < age Then FareType = "adult" : CanBuyAlcohol = true Else CanBuyAlcohol = false
ConditionalBranch2.java
switch (num) {
case 1:
gender = "male";
break;
case 2:
gender = "Female";
break;
case 3:
gender = "Other";
break;
default:
gender = "Unanswered";
break;
}
The expression of the switch statement (num
above) is only basic type + String type (Java SE 7 or later).
ConditionalBranch2.vb
Select Case Num
Case 1
Gender = "male"
Case 2
Gender = "Female"
Case 3
Gender = "Other"
Case Else
Gender = "Unanswered"
End Select
ConditionalBranch3.java
switch (phoneNumberPrefix) {
case 090:
case 080:
case 070:
isMobile = true;
break;
default:
isMobile = false;
break;
}
ConditionalBranch3.vb
Select Case PhoneNumberPrefix
Case 090, 080, 070
IsMobile = true
Case Else
IsMobile = false
End Select
ConditionalBranch4.java
//You can't do it with Java's Switch statement (if you do, you have to bite another variable)
ConditionalBranch4.vb
Select Case MonthNumber
Case 3 To 5
Season = "spring"
Case 6 To 8
Season = "summer"
Case 9 To 11
Season = "autumn"
Case Else
Season = "winter"
End Select
ConditionalBranch5.java
//Cannot be done with Java Switch statement (it is better to use if statement obediently)
ConditionalBranch5.vb
Select Case Score
Case Is < 60
Grade = "F"
Case Is < 70
Grade = "C"
Case Is < 80
Grade = "B"
Case Is < 90
Grade = "A"
Case Else
Grade = "S"
End Select
ForLoop.java
for (int i = 0; i <= 9; i++) {
System.out.println(i + "This is the second iterative process");
}
ForLoop.vb
For i As Integer = 0 To 9 Step 1 'If the increment value is 1, Step can be omitted.
Debug.WriteLine(i & "This is the second iterative process")
Next
In both languages, you can use variables declared outside the For statement instead of declaring the loop counter inside the For statement initialization expression. In that case, the variable can be used even if the For statement is exited.
ForLoop2.java
int i;
for (i = 0; i <= 9; i++) {
System.out.println(i + "This is the second iterative process");
}
System.out.println(i + "Repeated times");
ForLoop2.vb
Dim i As Integer
For i = 0 To 9 Step 1 'If the increment value is 1, Step can be omitted.
Debug.WriteLine(i & "This is the second iterative process")
Next
Debug.WriteLine(i & "Repeated times")
ForEachLoop.java
int[] scoreArray = {70, 80, 90};
//Normal for statement
for (int i = 0; i < scoreArray.length(); i++) {
System.out.println(scoreArray[i]);
}
//Extended for statement
for (int score : scoreArray) {
System.out.println(score);
}
ForEachLoop.vb
Dim ScoreArray() As Integer = {70, 80, 90}
'Normal for statement
For i As Integer = 0 To UBound(ScoreArray)
Debug.WriteLine(ScoreArray(i))
Next
'For Each statement
For Each score As Integer In ScoreArray
Debug.WriteLine(score)
Next
Continues execution as long as the condition is true.
WhileLoop.java
int i = 0;
while (i < 10) {
System.out.println(i + "This is the second iterative process");
i++;
}
WhileLoop.vb
Dim i As Integer = 0
While i < 10
Debug.WriteLine(i & "This is the second iterative process")
i += 1
End While
DoWhileLoop.java
Random rd = new Random();
int num = 0;
do {
num = rd.nextInt(100) + 1;
System.out.println(num);
} while (num % 2 == 0);
DoLoopWhile.vb
Dim rd As Random = new Random()
Dim Num As Integer = 0
Do
Num = rd.Next(1, 100)
Debug.WriteLine(Num)
Loop While Num Mod 2 = 0
In VB, in addition to the Loop While condition
(repeats until the condition becomes false), you can also use the ** Loop Until condition
** (repeats until the condition becomes true).
DoLoopUntil.vb
Dim rd As Random = new Random()
Dim Num As Integer = 0
Do
Num = rd.Next(1, 100)
Debug.WriteLine(Num)
Loop Until Num Mod 2 <> 0
ʻUntilThe following conditions are reversed, but both
DoLoopWhile.vb and
DoLoopUntil.vb` have the same processing.
DoLoopWhile2.vb
Dim i As Integer = 0
Do While i < 10
Debug.WriteLine(i & "This is the second iterative process")
i += 1
Loop
DoLoopUntil2.vb
Dim i As Integer = 0
Do Until i >= 10
Debug.WriteLine(i & "This is the second iterative process")
i += 1
Loop
break;
Exit Do
、Exit For
、Exit While
continue;
Continue Do
、Continue For
、Continue While
Note that the numbers specified in parentheses have different meanings.
ArrayDecralation.java
int[] numArray = new int[5];
It is an array with a total of ** 5 elements ** of indexes 0
, 1
, 2
, 3
, 4
.
The [n]
specifies ** the number of elements in the array **.
ArrayDeclaration.vb
Dim NumArray(4) As Integer
It is an array with a total of 5 elements with indexes 0
, 1
, 2
, 3
, ** 4
**.
The (n)
specifies the ** maximum index value **.
ArrayInit.java
int[] numArray = { 10, 20, 30, 40, 50 };
ArrayInit.vb
Dim NumArray() As Integer = { 10, 20, 30, 40, 50 }
ArrayUse.java
numArray[3] = 31;
int a = numArray[3];
ArrayUse.vb
NumArray(3) = 31
Dim a As Integer = NumArray(3)
MultiDArray.vb
int[][] numArray = new int[3][4];
double[][] doubleArray = { { 0.0, 0.1, 0.2 }, { 1.1, 2.2, 3.3, 4.4 } };
MultiDArray.vb
Dim NumArray(2, 3) As Integer
Dim DoubleArray(, ) As Double = { { 0.0, 0.1, 0.2 }, { 1.1, 2.2, 3.3, 4.4 } }
At first glance, (,)
seems to have forgotten to enter the maximum index value, but it is equivalent to [] []
in Java.
In Java, you cannot change the size of an array once created, you have to create a new array and transfer the values to it.
However, in VB you can resize the array by using the ** ReDim
statement **.
ChangeArraySize.vb
Dim NumArray(9) As Integer
' ...
ReDim Preserve NumArray(6)
With Preserve
, the value of the original element is preserved (** otherwise all elements will be empty **).
When the number of elements is reduced, the reduced elements are deleted (in the above example, the three elements of indexes 7
, 8
, and 9
are deleted).
array name.length
(returns the number of elements).ArrayLength.java
int[] numArray = new int[5];
for (int i = 0; i < numArray.length; i++) {
numArray[i] = i;
}
//The contents of the array{0, 1, 2, 3, 4}become
array name.Length
(returns ** number of elements **).
--If you want to process all elements repeatedly, use ʻUBound (array name) (** returns the maximum index value **). --**
To ** in the For statement means **
<= ** instead of
<. --Therefore, if you write
0 To array name.Length, it will break through the length of the array in the final round and become
System.IndexOutOfRangeException. --If you really don't want to remember ʻUBound ()
, you have to use array name.Length ―― 1
, but ...ArrayLength.java
Dim NumArray(4) As Integer
For i As Integer = 0 To UBound(NumArray)
NumArray(i) = i
Next
'The contents of the array{0, 1, 2, 3, 4}become
Basically, even if you think that "method" = "procedure", there is no problem in practical use.
In Java, only "methods" appear, whereas in VB, both words appear. What they are doing is the same "combining a series of processes", but "method" seems to be a word that is conscious of its affiliation in the procedure.
The feeling of "property" (field) and "** function " ( method **) of "object".
However, when I google "what is the difference between a method and a procedure in visual basic" in English, only the pages that say "function vs procedure" instead of "method vs procedure" are hit (method =). function?) This area seems to be related to the history of programming languages (function function and subroutine subroutine).
-Understand terms such as VBA macros, procedures, and methods accurately --t-hom ’s diary -Functions, methods, procedures. What is the difference between them? --Blank? = False
Target | Java | VB |
---|---|---|
Processing that does not return a return value | Method (void ) |
Sub Procedure |
Process that returns a return value | Method (void Other than) |
Function Procedure |
Processing to read and write class fields | getter /setter method |
Property Procedure |
Processes that belong to individual instances | Instance method | (UsualSub /Function Procedure) |
Processing that belongs to the entire class | static Method |
share(Shared )Method |
Processing according to the event | N/A | Event handler (a form of Sub procedure) |
** Do not return ** processing. (Since there is no direct return value, it is possible to rewrite variables and objects existing in the caller and return data by passing by reference.)
-** Java **: access modifier [static] void name (type name argument name, ...) {
~ }
VoidMethod.java
public void showMessage(int a, int b) {
System.out.println(a + b);
}
-** VB **: Access modifier [Shared] Sub name (argument name As type name, ...)
~ ʻEnd Function --Event handlers also belong here (those with a
Handles` clause at the end)
SubProc.vb
Public Sub ShowMessage(Str1 As String, Str2 As String)
Debug.WriteLine(a + b)
End Sub
** Return ** processing of the return value.
-** Java **: Access modifier [static] Return type name (type name argument name, ...) {
~}
--Specify the return value with return
ReturnMethod.java
public int doCalc(int a, int b) {
return a * b;
}
-** VB **: Access modifier [Shared] Function name (argument name As type name, ...) As return type
~ ʻEnd Function --Specify the return value with
Return`
FunctionProc.vb
Public Function DoCalc(a As Integer, b As Integer) As Integer
Return a * b
End Function
→ Explanation in the item of class
ExitMethod.java
public void showMessage() {
if (errFlag) {
return; //Actually, even the void method can be exited with this
} else {
System.out.println("Successful processing")
}
}
public int doCalc(int a, int b) {
int result = a * b;
if (result > 10) {
return 0; //It is not allowed to exit without returning a value
} else {
return result;
}
}
ExitProcedure.vb
Public Sub ShowMessage()
If ErrFlag Then
Exit Sub 'Exit Sub in VB
Else
Debug.WriteLine("Successful processing")
End Sub
Public Function DoCalc(a As Integer, b As Integer) As Integer
Dim result As Integer = a * b
If (result > 10) Then
Exit Function 'Returns 0 because the return value is an Integer type
ElseIf (result > 50) Then
DoCalc = result + 1
Exit Function 'Returns the value set in the variable DoCalc
Else
Return result
End If
End Function
In Java, it is impossible to exit a method other than void without return
, but it can be done in VB's Function procedure.
However, depending on the return type, it may cause unexpected behavior such as causing a Nullpo exception, so it seems that you should always Return
.
-** Java: ** Set the argument to (data type ... variable name)
--In the method, it can be treated like an array variable.
--Variadic arguments must be placed at the end of the argument list if other arguments are also specified
VariadicMethod.java
public static int getSum(int... numbers) {
int sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum += numbers[i];
}
return sum;
}
-** VB **: (ParamArray variable name As data type [])
--The nature is the same as Java.
VariadicFunction.vb
Public Shared Function GetSum(ParamArray Numbers As Integer[]) As Integer
Dim Sum As Integer = 0
For i As Integer = 0 To UBound(Numbers)
Sum += Numbers(i)
Next i
Return sum;
End Function
-How to create a method with variadic arguments? [C # / VB]: .NET TIPS-@IT
Arguments that can be omitted at the time of calling.
-** Java **: (Maybe) I don't have it as a language specification.
--The ʻOptionaltype introduced in Java 8 is a completely different concept and should not be confused. -** VB **:
(Optional variable name As data type = default)`
--If omitted at the time of calling, the default value is assumed to have been passed.
--So you need to specify the default value.
--All arguments of argument migration with Optional specified must be Optional (write Optional arguments after writing all the arguments that cannot be omitted)
--It is OK to provide multiple Optional arguments.
OptionalArguments.vb
Public Shared Function Calc(Num1 As Integer, Num2 As Integer, Optional CalcMethod As Integer = 0)
If CalcMethod = 0 Then
Return Num1 + Num2
ElseIf CalcMethod = 1 Then
Return Num1 - Num2
ElseIf CalcMethod = 2 Then
Return Num1 * Num2
ElseIf CalcMethod = 3 Then
Return Num1 / Num2
Else
Return 0
End If
End Function
In this example, if you call it like Calc (5, 10)
, the pattern of CalcMethod = 0
(that is, addition) is executed.
-** Java **: You can only return the object in a class.
ReturnMultiValue.java
public static Result getResult(int a, int b) {
Result result = new Result();
result.setSum(a + b);
result.setDiff(a - b);
result.setProduct(a * b);
result.setQuotient((double) a / b);
Return result;
}
Result.java
public Class Result {
int Sum;
int Diff;
int Product;
double Quotient;
// getter / setter
}
-** VB **: ** Tuple ** can be used to return multiple values --Tuple: A collection of multiple variables on the spot ――Is it easy to understand if you have the image of creating a temporary class?
Tuple.vb
Public Sub Main()
'Declare tuples with names
Dim Result As (Sum As Integer, Diff As Integer, Product As Integer, Quotient As Double)
Result = GetResult(5, 10)
'Use the value in the tuple
Debug.WriteLine(Result.Sum)
Debug.WriteLine(Result.Diff)
Debug.WriteLine(Result.Product)
Debug.WriteLine(Result.Quotient)
End Sub
'Function procedure that returns a tuple
Public Shared Function GetResult(a As Integer, b As Integer) As (Integer, Integer, Integer, Double)
Return (a + b, a - b, a * b, a / c)
End Function
The first method to be executed when the program is started.
In Java, the method named main is always the entry point, but in VB this is not always the case. When you create a Windows Forms project, the first form you create becomes the entry point. For how to change this, click Create Java main method in VB.NET! | Rise Will Staff Blog is detailed.
-** Java class ** public class Main {}
--Field
--Method
--getter
/ setter
method
JavaClass.java
public class JavaClass {
//Field (state of the object/(Indicating the nature)
private int field;
//Method (indicating the behavior / behavior of an object)
public void method(){
// ...
}
//Method>getter (provides reading of encapsulated private fields)
public int getField() {
return field;
}
//Method>setter (provides the ability to write to encapsulated private fields)
public void setField(int value) {
this.field = value;
}
}
-** VB class ** Public Class Main ... End Class
--Field (member variable)
--May be prefixed with _
to distinguish it from properties
--Properties
--Get
procedure
--Set
procedure
--Procedure (method)
--Event
VBClass.vb
Public Class VBClass
'Field (member variable)
Dim _field As Integer
'Property
Property field() As Integer
Get
Return _field
End Get
Set(ByVal value As Integer)
_field = value
End Set
End Property
'Procedure
Public Sub Procedure()
' ...
End Sub
End Class
A property is a collection of getter / setter methods in Java (it is possible to implement only one of the Get procedure and Set procedure). It differs from Java in that properties are ** treated like fields from outside the class **.
For example, when accessing the private field field
of the above sample code JavaClass.java
from another class, you need to write the following code.
AccessToField.java
public class Main {
public static void main(String[] args) {
JavaClass jc = new JavaClass();
//The following two lines will result in a compile error
int num = jc.field;
jc.field = 100;
//Instead, write
int num = jc.getField();
jc.setField(100);
}
}
In this way, access is denied with object variable name.field name
, so instead, receive the field contents as the return value of the getter method, or rewrite the field contents by passing the value as an argument to the setter method. It becomes the method.
If you write a movement similar to this in VB, it will be like this.
AccessToField.vb
Public Class Main
Public Shared Sub Main
Dim vbc As New VBClass()
Dim num As Integer = vbc.field 'Get call
vbc.field = 100 'Set call
End Sub
End Class
Writing a property name like a field implicitly calls the Get / Set procedure defined for that property.
If the property simply returns / writes a value, you can simplify the code by using ** auto-implemented property **.
AutoImplProperty.vb
Public Class AutoImplProperty
Public Property Name As String
Public Property Owner As String = "DefaultName"
Public Property Items As New List(Of String) From {"M", "T", "W"}
Public Property ID As New Guid()
End Class
(From Automatic Implementation Properties --Visual Basic | Microsoft Docs )
At this time, a hidden Private field (** backing field **) with _
added to the property name is automatically created. In the above example, backing fields _Name
, _Owner
, _Items
, _ID
are created (so if you declare a field with the same name yourself, you will get a compile error).
Also, ** properties do not have to have a one-to-one correspondence with fields **. In other words, you can pick up values from multiple fields and concatenate them to treat them like a single field. It is also possible to receive one set of values and actually divide it into two or more fields and store them. (Of course, you need to define a Get / Set procedure that matches it).
There was an easy-to-understand example in Microsoft Docs, so I will quote it (Public Class
~ ʻEnd Class` is added so that it is easy to understand that it is a member in the class).
The following property stores the full name as two component names (first name and last name). When the calling code reads fullName, the Get procedure joins the two component names and returns the full name. When the calling code assigns a new full name, the Set procedure attempts to split it into two component names. If no space is found, everything is stored as a name. .. Property Procedures --Visual Basic | Microsoft Docs
CombinedProperty.vb
Public Class CombinedProperty
Dim firstName, lastName As String
Property fullName() As String
Get
If lastName = "" Then
Return firstName
Else
Return firstName & " " & lastName
End If
End Get
Set(ByVal Value As String)
Dim space As Integer = Value.IndexOf(" ")
If space < 0 Then
firstName = Value
lastName = ""
Else
firstName = Value.Substring(0, space)
lastName = Value.Substring(space + 1)
End If
End Set
End Property
End Class
Caller:
CallProperty.vb
fullName = "MyFirstName MyLastName"
MsgBox(fullName)
For other differences between properties and member variables, see the following page.
--[Differences between properties and variables --Visual Basic | Microsoft Docs](https://docs.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/differences-between-properties] -and-variables)
Recommended Posts