From Java to VB.NET-Writing Contrast Memo-

About this article

Background of creation

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.

Target person / purpose

--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).

environment

That said, there should be almost no code that depends on the environment.

Precautions for description

--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.

References (general)

--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

Basic structure of code

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

Comment.java


//Singular line comment

/*
 *Multi-line comment
 */

Comment.vb


'Singular line comment

Documentation comments

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

reference

--Insert XML document comments --Visual Studio | Microsoft Docs

File / folder structure

Java (Eclipse) example

VB.NET Windows Forms Application (Visual Studio) Example

Visual Studio allows you to combine multiple projects into a ** solution **. (Although there is also a ** working set ** in Eclipse)

variable

Data type classification

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.

Declaration / Access Qualification

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.

Variable name rules

letter Java VB Remarks
Half-width alphanumeric characters
Japanese characters Of course not recommended
_ underscore
& ×
Numbers at the beginning × ×

Initialization

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 declaration

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

reference

-Data Type Overview (Visual Basic) | Microsoft Docs

operator

Arithmetic operator

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 \ 5The result of4become
Surplus (remainder) a % b a Mod b 23 % 5Or23 Mod 5The result of3become
Exponentiation (None as an operator) a ^ b VB^Note that is the highest priority of arithmetic operators
Increment ++aOra++ N/A In VBa += 1There is no choice but to write
Increment --aOra-- N/A In VBa -= 1There is no choice but to write

Division between integers

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 asdouble` 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

Exponentiation in Java

In Java, use java.lang.Math.pow (a, b). The first argument ʻais the base and the second argumentb is the exponent (that is, ʻa ^ b in VB).

Assignment operator

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)

Comparison operator

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

Logical operator

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 ... `

Concatenation operator

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 reference page

-Operator | Introduction to Java Code --Operators --Visual Basic | Microsoft Docs

Type conversion

Conditional branch

if statement / if statement

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

Switch / Select Case statement

Match with one value

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

Match multiple values

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

Specify a range of values

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

Use comparison operators

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

repetition

for statement / For statement

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")

Extended for statement / For-Each statement

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

while statement / While-End While statement

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

do-while statement / Do-Loop statement

Post-judgment type (executed once)

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 bothDoLoopWhile.vb and DoLoopUntil.vb` have the same processing.

Pre-judgment type (may not be executed even once)

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 out of the loop

Proceed to the next repetition on the way

Array

Declaration

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 **.

Initialization

ArrayInit.java


int[] numArray = { 10, 20, 30, 40, 50 };

ArrayInit.vb


Dim NumArray() As Integer = { 10, 20, 30, 40, 50 }

Substitution / use

ArrayUse.java


numArray[3] = 31;

int a = numArray[3];

ArrayUse.vb


NumArray(3) = 31

Dim a As Integer = NumArray(3)

Multidimensional array

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.

Change array size

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 length (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

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

Method / procedure

Organize concepts (not completely organized)

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).

reference

-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

Comparison of terms

Target Java VB
Processing that does not return a return value Method (void SubProcedure
Process that returns a return value Method (voidOther than) FunctionProcedure
Processing to read and write class fields getter/setter method PropertyProcedure
Processes that belong to individual instances Instance method (UsualSub/FunctionProcedure)
Processing that belongs to the entire class staticMethod share(Shared)Method
Processing according to the event N/A Event handler (a form of Sub procedure)

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 aHandles` clause at the end)

SubProc.vb


Public Sub ShowMessage(Str1 As String, Str2 As String)
    Debug.WriteLine(a + b)
End Sub

Function procedure

** 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 withReturn`

FunctionProc.vb


Public Function DoCalc(a As Integer, b As Integer) As Integer
    Return a * b
End Function

Property procedure

→ Explanation in the item of class

Exit the procedure in the middle

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.

Variadic argument

-** 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 

Variadic arguments references

-How to create a method with variadic arguments? [C # / VB]: .NET TIPS-@IT

Option argument

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.

Receive multiple values as return values

-** 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

Entry point

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.

class

Constitution

-** 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

Learn more about properties

Basic

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.

Auto-implemented properties

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).

Property: Field = 1: n is also OK

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

From Java to VB.NET-Writing Contrast Memo-
Memo for migration from java to kotlin
Changes from Java 8 to Java 11
Sum from Java_1 to 100
From Java to Ruby !!
New features from Java7 to Java8
Connect from Java to PostgreSQL
From Ineffective Java to Effective Java
[Personal memo] Frequently used Java grammar updated from time to time
Java memo
Java to be involved from today
Java, interface to start from beginner
The road from JavaScript to Java
[Java] Conversion from array to List
Convert from java UTC time to JST time
Connect from Java to MySQL using Eclipse
From installing Eclipse to executing Java (PHP)
Post to Slack from Play Framework 2.8 (Java)
Java: How to send values from Servlet to Servlet
[Java] Flow from source code to execution
Introduction to monitoring from Java Touching Prometheus
Precautions when migrating from VB6.0 to JAVA
Type conversion from java BigDecimal type to String type
java anything memo
Java Silver memo
java, maven memo
Java SE 7 memo
[Java] Introduction to Java
Introduction to java
Java specification memo
Java pattern memo
[Java] From two Lists to one array list
Upsert from Java SDK to Azure Cosmos DB
Run R from Java I want to run rJava
Connect to Aurora (MySQL) from a Java application
To become a VB.net programmer from a Java shop
Migrate from Java to Server Side Kotlin + Spring-boot
How to get Class from Element in Java
[Java] How to switch from open jdk to oracle jdk
I want to write quickly from java to sqlite
Minecraft BE server development from PHP to Java
[Java] Memo on how to write the source
Select * from Java SDK to Azure Cosmos DB
Launch Docker from Java to convert Office documents to PDF
Call Java from JRuby
Convert Java enum enums and JSON to and from Jackson
How to jump from Eclipse Java to a SQL file
How to write Scala from the perspective of Java
Migrate from JUnit 4 to JUnit 5
Sum from Java_1 to 100
java basic knowledge memo
Java learning memo (method)
[Java] How to extract the file name from the path
Aiming to acquire Java Oracle Silver, point memo (pass)
Eval Java source from Java
[Java] Connect to MySQL
[Java ~ Method ~] Study memo (5)
java se 8 programmer Ⅰ memo
Java paid private memo
6 features I missed after returning to Java from Scala
Kotlin's improvements to Java