Java Why is It Easy to Differentiate Between Calls to Instance Methods and Calls to Static Methods
<< Back to JAVA
Java Method Examples: Instance and Static
Use instance and static methods. Review overloaded method syntax.
Methods. In structured programming, logic is divided, into parts, into methods. We call methods, which themselves call further methods.
Program logic. With methods, we condense and simplify program logic. This makes programs easier to modify and to understand—more versatile.
Static. This program has two static methods. The methods are static because they do not require an object instance. The two methods compute lengths.Static
TotalLength: We see how to directly call a method. We call the totalLength method from main.
AverageLength: With averageLength(), we call another method. This shows methods can call methods.
Info: AverageLength depends on totalLength. Suppose totalLength() is changed. AverageLength() will automatically implement this change.
Java program that introduces methods public class Program { static int
totalLength (String a, String b) { // Add up lengths of two strings. return a.length() + b.length(); } static int
averageLength (String a, String b) { // Divide total length by 2. return totalLength(a, b) / 2; } public static void main(String[] args) { // Call methods. int total = totalLength("Golden", "Bowl"); int average = averageLength("Golden", "Bowl"); System.out.println(total); System.out.println(average); } } Output 10 5
Overload. A method can have one name, but many argument lists, many implementations. This is called overloading. Each method is separate, but the name is shared.Overload
So: We do not need to remember a different name for "action" in this program. Each call is inferred by its arguments—an int, a String.
Strings
Java program that overloads methods public class Program { public static void
action (int value) { System.out.println("Int = " + Integer.toString(value)); } public static void
action (String value) { System.out.println("Length = " + value.length()); } public static void main(String[] args) { // Call with Integer argument. action(1); // Call with String argument. action("cat"); } } Output Int = 1 Length = 3
Instance methods. These are accessed through an instance of a class, not the class type itself. So if we have a size() method on an Item, we must first create an instance of the Item class.
Tip: Methods are by default instance and private. We make the method here public, but leave it as an instance method.
Java program that calls instance method class Item { public int size() { // An instance method. return 10; } } public class Program { public static void main(String[] args) { // The size method can only be accessed from an instance. Item item = new Item(); int value = item.
size (); System.out.println(value); } } Output 10
Public, private. A method can specify how accessible it is to other parts of the program. A public method is accessible everywhere. A private method can only be called from the same class.
Public: Many classes require entry points other than the constructor. A public method, like apply() here, is an entry point.
Private: Classes contain internal, class-only implementation logic. Private methods work well for this purpose.
Default: The default is package-based. So when you don't specify public or private, the method can be used throughout the entire package.
Java program that uses public, private methods class Test {
public void apply() { System.out.println("Apply called"); this.validate(); }
private void validate() { System.out.println("Validate called"); } } public class Program { public static void main(String[] args) { // Create new Test and call public method. Test t = new Test(); t.apply(); // Cannot call a private method: // t.validate(); } } Output Apply called Validate called
Protected. A method that is protected is accessible to any child classes. So if a class extends another, it can access protected methods in it.
Note: The default accessibility also allows this. But protected makes this concept explicit.
Java program that uses protected method class Widget {
protected void display() { System.out.println(true); } } class SubWidget extends Widget { public void use() { // A subclass can use a protected method in the base class. // ... It cannot use a private one. super.display(); } } public class Program { public static void main(String[] args) { SubWidget sub = new SubWidget(); sub.use(); } } Output true
Return. In non-void methods, a return value must be supplied. This must match the declaration of the method. So the getName method here must return a String.Return
Java program that uses return statement public class Program { static String getName() { // This method must return a String.
return "Augusta"; } public static void main(String[] args) { String name = getName(); System.out.println(name); } } Output Augusta
Void. This term means "no return value." So a void method returns no value—it can use an empty return statement. An implicit return is added at the end.
Java program that has void method public class Program { static
void test(int value) { if (value == 0) { // A void method has no return value. // ... We use an empty return statement. return; } System.out.println(value); // A return statement is automatically added here. } public static void main(String[] args) { // No variables can be assigned to a void method call. test(0); // No effect. test(1); } } Output 1
Boolean method. A boolean (or predicate) method returns true or false. In classes, we often have public boolean methods (like isFuzzy here) that reveal information about a class's state.
Here: We instantiate a Cat object. We then call its isFuzzy boolean method, which always returns true.
Important: This design can be useful in real programs. For example, some Cats might be hairless—isFuzzy would return false.
Java program that uses boolean method class Cat { public boolean
isFuzzy () { return true; } } public class Program { public static void main(String[] args) { Cat c = new Cat(); // Call boolean instance method. if (c.
isFuzzy ()) { System.out.println(true); } } } Output true
Variable argument lists. A method can receive an array of arguments of any length. These array elements can be passed directly at the call site.
Varargs: In older languages like C, this syntax was called varargs. In C# we use the params keyword.
Ellipsis: The ellipsis (three dots) indicates a variable-length array of the type. So the displayAll method receives an int array.
Quote: In computer programming, a variadic function is a function of indefinite arity... one which accepts a variable number of arguments.
Variadic function: Wikipedia
Java program that uses variable argument list syntax public class Program { static void displayAll(int... test) { // The argument is an int array. for (int value : test) { System.out.println(value); } System.out.println("DONE"); } public static void main(String[] args) { // Pass variable argument lists to displayAll method. displayAll(10, 20, 30); displayAll(0); displayAll(); } } Output 10 20 30 DONE 0 DONE DONE
Interface methods. A method can be invoked through an interface reference. This often incurs a performance cost. But it can help unify a program's construction.Interfaces
Optional. With this class, we can call methods with optional arguments. Some extra code complexity is required, but we can avoid using invalid values.Optional
Lambda. The Java language supports lambda expressions. With a lambda, we specify with concise syntax a function object. These help with smaller tasks.Lambda
Methods are critical. We use them throughout software. We prefer instance methods where appropriate. Static methods too are often useful. With methods we construct reusable logic pieces.
Related Links:
- Java Continue Keyword
- Java Convert Char Array to String
- Java Combine Arrays
- Java Console Examples
- Java Web Services Tutorial
- Java Odd and Even Numbers: Modulo Division
- Java IO
- Java 9 Features
- Java 8 Features
- Java String
- Java Regex | Regular Expression
- Java Filename With Date Example (Format String)
- Java Applet Tutorial
- Java Files.Copy: Copy File
- Java filter Example: findFirst, IntStream
- Java Final and final static Constants
- Java Super: Parent Class
- Java Date and Time
- Java do while loop
- Java Break
- Java Continue
- Java Comments
- Java Splitter Examples: split, splitToList
- Java Math.sqrt Method: java.lang.Math.sqrt
- Java Reflection
- Java Convert String to int
- JDBC Tutorial | What is Java Database Connectivity(JDBC)
- Java main() method
- Java HashMap Examples
- Java HashSet Examples
- Java Arrays.binarySearch
- Java Integer.bitCount and toBinaryString
- Java Overload Method Example
- Java First Words in String
- Java Convert ArrayList to String
- Java Convert boolean to int (Ternary Method)
- Java regionMatches Example and Performance
- Java ArrayDeque Examples
- Java ArrayList add and addAll (Insert Elements)
- Java ArrayList Clear
- Java ArrayList int, Integer Example
- Java ArrayList Examples
- Java Boolean Examples
- Java break Statement
- Java Newline Examples: System.lineSeparator
- Java Stream: Arrays.stream and ArrayList stream
- Java charAt Examples (String For Loop)
- Java Programs | Java Programming Examples
- Java OOPs Concepts
- Java Naming Conventions
- Java Constructor
- Java Class Example
- Java indexOf Examples
- Java Collections.addAll: Add Array to ArrayList
- Java Compound Interest
- Java Int Array
- Java Interface Examples
- Java 2D Array Examples
- Java Remove HTML Tags
- Java Stack Examples: java.util.Stack
- Java Enum Examples
- Java EnumMap Examples
- Java StackOverflowError
- Java startsWith and endsWith Methods
- Java Initialize ArrayList
- Java Object Array Examples: For, Cast and getClass
- Java Objects, Objects.requireNonNull Example
- Java Optional Examples
- Java Static Initializer
- Java static Keyword
- Java Package: Import Keyword Example
- Java Do While Loop Examples
- Java Double Numbers: Double.BYTES and Double.SIZE
- Java Truncate Number: Cast Double to Int
- Java Padding: Pad Left and Right of Strings
- Java Anagram Example: HashMap and ArrayList
- Java Math.abs: Absolute Value
- Java Extends: Class Inheritance
- Java String Class
- Java String Switch Example: Switch Versus HashMap
- Java StringBuffer: append, Performance
- Java Array Examples
- Java Remove Duplicates From ArrayList
- Java if, else if, else Statements
- Java Math.ceil Method
- Java This Keyword
- Java PriorityQueue Example (add, peek and poll)
- Java Process.start EXE: ProcessBuilder Examples
- Java Palindrome Method
- Java parseInt: Convert String to Int
- Java toCharArray: Convert String to Array
- Java Caesar Cipher
- Java Array Length: Get Size of Array
- Java String Array Examples
- Java String compareTo, compareToIgnoreCase
- Java String Concat: Append and Combine Strings
- Java Cast and Convert Types
- Java Math.floor Method, floorDiv and floorMod
- Java Math Class: java.lang.Math
- Java While Loop Examples
- Java Reverse String
- Java Download Web Pages: URL and openStream
- Java Math.pow Method
- Java Math.round Method
- Java Right String Part
- Java MongoDB Example
- Java Substring Examples, subSequence
- Java Prime Number Method
- Java Sum Methods: IntStream and reduce
- Java switch Examples
- Java Convert HashMap to ArrayList
- Java Remove Duplicate Chars
- Java Constructor: Overloaded, Default, This Constructors
- Java String isEmpty Method (Null, Empty Strings)
- Java Regex Examples (Pattern.matches)
- Java ROT13 Method
- Java Random Number Examples
- Java Recursion Example: Count Change
- Java reflect: getDeclaredMethod, invoke
- Java Count Letter Frequencies
- Java ImmutableList Examples
- Java String equals, equalsIgnoreCase and contentEquals
- Java valueOf and copyValueOf String Examples
- Java Vector Examples
- Java Word Count Methods: Split and For Loop
- Java Tutorial | Learn Java Programming
- Java toLowerCase, toUpperCase Examples
- Java Ternary Operator
- Java Tree: HashMap and Strings Example
- Java TreeMap Examples
- Java while loop
- Java Convert String to Byte Array
- Java Join Strings: String.join Method
- Java Modulo Operator Examples
- Java Integer.MAX VALUE, MIN and SIZE
- Java Lambda Expressions
- Java lastIndexOf Examples
- Java Multiple Return Values
- Java String.format Examples: Numbers and Strings
- Java Joiner Examples: join
- Java Keywords
- Java Replace Strings: replaceFirst and replaceAll
- Java return Examples
- Java Multithreading Interview Questions (2021)
- Java Collections Interview Questions (2021)
- Java Shuffle Arrays (Fisher Yates)
- Top 30 Java Design Patterns Interview Questions (2021)
- Java ListMultimap Examples
- Java String Occurrence Method: While Loop Method
- Java StringBuilder capacity
- Java Math.max and Math.min
- Java Factory Design Pattern
- Java StringBuilder Examples
- Java Mail Tutorial
- Java Swing Tutorial
- Java AWT Tutorial
- Java Fibonacci Sequence Examples
- Java StringTokenizer Example
- Java Method Examples: Instance and Static
- Java String Between, Before, After
- Java BitSet Examples
- Java System.gc, Runtime.getRuntime and freeMemory
- Java Character Examples
- Java Char Lookup Table
- Java BufferedWriter Examples: Write Strings to Text File
- Java Abstract Class
- Java Hashtable
- Java Math class with Methods
- Java Whitespace Methods
- Java Data Types
- Java Trim String Examples (Trim Start, End)
- Java Exceptions: try, catch and finally
- Java vs C#
- Java Float Numbers
- Java Truncate String
- Java Variables
- Java For Loop Examples
- Java Uppercase First Letter
- Java Inner Class
- Java Networking
- Java Keywords
- Java If else
- Java Switch
- Loops in Java | Java For Loop
- Java File: BufferedReader and FileReader
- Java Random Lowercase Letter
- Java Calendar Examples: Date and DateFormat
- Java Case Keyword
- Java Char Array
- Java ASCII Table
- Java IntStream.Range Example (Get Range of Numbers)
- Java length Example: Get Character Count
- Java Line Count for File
- Java Sort Examples: Arrays.sort, Comparable
- Java LinkedHashMap Example
- Java Split Examples
Related Links
Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf
Source: https://thedeveloperblog.com/java/method-java
0 Response to "Java Why is It Easy to Differentiate Between Calls to Instance Methods and Calls to Static Methods"
Enregistrer un commentaire