GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Python Technologies
  • Databases
  • Computer Programming
  • Web Development
  • Java Technologies
  • Computer Science
  • Mobile Development
  • Big Data & Analytics
  • Microsoft Technologies
  • DevOps
  • Latest Technologies
  • Machine Learning
  • Digital Marketing
  • Software Quality

This view

  • Original page
  • New address

GeezerVison is showing www.tutorialspoint.com — Java - Class Methods

Java Tutorial
  • Java - Home
  • Java - Overview
  • Java - History
  • Java - Features
  • Java Vs. C++
  • JVM - Java Virtual Machine
  • Java - JDK vs JRE vs JVM
  • Java - Environment Setup
  • Java - Hello World Program
  • Java - Comments
  • Java - Basic Syntax
  • Java - Variables
  • Java - Data Types
  • Java - Type Casting
  • Java - Unicode System
  • Java - User Input
  • Java - Date & Time
  • Java Operators
  • Java - Operators
  • Java - Arithmetic Operators
  • Java - Assignment Operators
  • Java - Relational Operators
  • Java - Logical Operators
  • Java - Bitwise Operators
  • Java Operator Precedence & Associativity
  • Java - Unary Operators
  • Java Control Statements
  • Java - Decision Making
  • Java - If Else Statement
  • Java - Switch Statement
  • Java - Loop Control
  • Java - For Loop
  • Java - For-Each Loop
  • Java - While Loop
  • Java - Do While Loop
  • Java - Break Statement
  • Java - Continue Statement
  • Object Oriented Programming
  • Java - OOPs Concepts
  • Java - Object & Classes
  • Java - Class Attributes
  • Java - Class Methods
  • Java - Methods
  • Java - Variables Scope
  • Java - Constructors
  • Java - Access Modifiers
  • Java - Inheritance
  • Java - Aggregation
  • Java - Polymorphism
  • Java - Overriding
  • Java - Method Overloading
  • Java - Dynamic Binding
  • Java - Static Binding
  • Java - Instance Initializer Block
  • Java - Abstraction
  • Java - Encapsulation
  • Java - Interfaces
  • Java - Packages
  • Java - Inner Classes
  • Java - Static Class
  • Java - Anonymous Class
  • Java - Singleton Class
  • Java - Wrapper Classes
  • Java - Enums
  • Java - Enum Constructor
  • Java - Enum Strings
  • Java Built-in Classes
  • Java - Number
  • Java - Boolean
  • Java - Characters
  • Java - Arrays
  • Java - Multi-Dimensional Arrays
  • Java - Final Arrays
  • Java - Math Class
  • Java File Handling
  • Java - Files
  • Java - Create a File
  • Java - Write to File
  • Java - Read Files
  • Java - Delete Files
  • Java - Directories
  • Java - I/O Streams
  • Java Error & Exceptions
  • Java - Exceptions
  • Java - try-catch Block
  • Java - try-with-resources
  • Java - Multi-catch Block
  • Java - Nested try Block
  • Java - Finally Block
  • Java - throw Exception
  • Java - Exception Propagation
  • Java - Built-in Exceptions
  • Java - Custom Exception
  • Java - Chained Exception
  • Java Multithreading
  • Java - Multithreading
  • Java - Thread Life Cycle
  • Java - Creating a Thread
  • Java - Starting a Thread
  • Java - Joining Threads
  • Java - Naming Thread
  • Java - Thread Scheduler
  • Java - Thread Pools
  • Java - Main Thread
  • Java - Thread Priority
  • Java - Daemon Threads
  • Java - Thread Group
  • Java - Shutdown Hook
  • Java Synchronization
  • Java - Synchronization
  • Java - Block Synchronization
  • Java - Static Synchronization
  • Java - Inter-thread Communication
  • Java - Thread Deadlock
  • Java - Interrupting a Thread
  • Java - Thread Control
  • Java - Reentrant Monitor
  • Java Networking
  • Java - Networking
  • Java - Socket Programming
  • Java - URL Processing
  • Java - URL Class
  • Java - URLConnection Class
  • Java - HttpURLConnection Class
  • Java - Socket Class
  • Java - Generics
  • Java Collections
  • Java - Collections
  • Java - Collection Interface
  • Java Interfaces
  • Java - List Interface
  • Java - Queue Interface
  • Java - Map Interface
  • Java - SortedMap Interface
  • Java - Set Interface
  • Java - SortedSet Interface
  • Java Data Structures
  • Java - Data Structures
  • Java - Enumeration
  • Java Collections Algorithms
  • Java - Iterators
  • Java - Comparators
  • Java - Comparable Interface in Java
  • Advanced Java
  • Java - Command-Line Arguments
  • Java - Lambda Expressions
  • Java - Sending Email
  • Java - Applet Basics
  • Java - Javadoc Comments
  • Java - Autoboxing and Unboxing
  • Java - File Mismatch Method
  • Java - REPL (JShell)
  • Java - Multi-Release Jar Files
  • Java - Private Interface Methods
  • Java - Inner Class Diamond Operator
  • Java - Multiresolution Image API
  • Java - Collection Factory Methods
  • Java - Module System
  • Java - Nashorn JavaScript
  • Java - Optional Class
  • Java - Method References
  • Java - Functional Interfaces
  • Java - Default Methods
  • Java - Base64 Encode Decode
  • Java - Switch Expressions
  • Java - Teeing Collectors
  • Java - Microbenchmark
  • Java - Text Blocks
  • Java - Dynamic CDS archive
  • Java - Z Garbage Collector (ZGC)
  • Java - Null Pointer Exception
  • Java - Packaging Tools
  • Java - Sealed Classes
  • Java - Record Classes
  • Java - Hidden Classes
  • Java - Pattern Matching
  • Java - Compact Number Formatting
  • Java - Garbage Collection
  • Java - JIT Compiler
  • Java Miscellaneous
  • Java - Recursion
  • Java - Regular Expressions
  • Java - Serialization
  • Java - Strings
  • Java - Process API Improvements
  • Java - Stream API Improvements
  • Java - Enhanced @Deprecated Annotation
  • Java - CompletableFuture API Improvements
  • Java - Marker Interface
  • Java - Streams
  • Java - Datetime Api
  • Java 8 - New Features
  • Java 9 - New Features
  • Java 10 - New Features
  • Java 11 - New Features
  • Java 12 - New Features
  • Java 13 - New Features
  • Java 14 - New Features
  • Java 15 - New Features
  • Java 16 - New Features
  • Java APIs & Frameworks
  • JDBC Tutorial
  • SWING Tutorial
  • AWT Tutorial
  • Servlets Tutorial
  • JSP Tutorial
  • Java Class References
  • Java - Scanner
  • Java - Arrays
  • Java - Strings
  • Java - Date
  • Java - ArrayList
  • Java - Vector
  • Java - Stack
  • Java - PriorityQueue
  • Java - LinkedList
  • Java - ArrayDeque
  • Java - HashMap
  • Java - LinkedHashMap
  • Java - WeakHashMap
  • Java - EnumMap
  • Java - TreeMap
  • Java - IdentityHashMap
  • Java - HashSet
  • Java - EnumSet
  • Java - LinkedHashSet
  • Java - TreeSet
  • Java - BitSet
  • Java - Dictionary
  • Java - Hashtable
  • Java - Properties
  • Java - Collection
  • Java - Array
  • Java Useful Resources
  • Java - Cheatsheet
  • Java - Questions and Answers
  • Java 8 - Questions and Answers
  • Java - Quick Guide
  • Java - Useful Resources
  • Java - Discussion
  • Java - Online Compiler
  • Java - Examples
Selected Reading
  • UPSC IAS Exams Notes
  • Developer's Best Practices
  • Questions and Answers
  • Online Resume Builder
  • HR Interview Questions
  • Computer Glossary
  • Who is Who

Java - Class Methods



Previous
Quiz
Next

Java Class Methods

The class methods are methods that are declared within a class. They perform specific operations and can access, modify the class attributes.

Creating (Declaring) Java Class Methods

Class methods declaration is similar to the user-defined methods declaration except that class methods are declared within a class.

The class methods are declared by specifying the access modifier followed by the return type, method_name, and parameters list.

Syntax

Use the below syntax to declare a Java class method:

public class class_name {
  modifier returnType nameOfMethod(Parameter List) {
    // method body
  }
}

The syntax shown above includes −

  • modifier − It defines the access type of the method and it is optional to use.

  • returnType − The returns data type of the class method.

  • nameOfMethod − This is the method name. The method signature consists of the method name and the parameter list.

  • Parameter List − The list of parameters, it is the type, order, and number of parameters of a method. These are optional, method may contain zero parameters.

  • method body − The method body defines what the method does with the statements.

Example

Here is the source code of the above defined method called minimum(). This method takes two parameters n1 and n2 and returns the minimum between the two −

class Util {
  /** the snippet returns the minimum between two numbers */
  public int minimum(int n1, int n2) {
    int min;
    if (n1 > n2)
      min = n2;
    else
      min = n1;

    return min;
  }
}

Accessing Java Class Methods

To access a class method (public class method), you need to create an object first, then by using the object you can access the class method (with the help of dot (.) operator).

Syntax

Use the below syntax to access a Java public class method:

object_name.method_name([parameters]);

Example

Following is the example to demonstrate how to define class method and how to access it. Here, We've created an object of Util class and call its minimum() method to get minimum value of given two numbers −

package com.tutorialspoint;

class Util {
   public int minimum(int n1, int n2) {
      int min;
      if (n1 > n2)
         min = n2;
      else
         min = n1;

      return min; 
   }
}
public class Tester {
   
   public static void main(String[] args) {
      int a = 11;
      int b = 6;

      Util util = new Util();
	  
      int c = util.minimum(a, b);
      System.out.println("Minimum Value = " + c);
   }
}

Output

Minimum value = 6

this Keyword in Java Class Methods

this is a keyword in Java which is used as a reference to the object of the current class, with in an instance method or a constructor. Using this you can refer the members of a class such as constructors, variables and methods.

Note − The keyword this is used only within instance methods or constructors

In general, the keyword this is used to −

  • Differentiate the instance variables from local variables if they have same names, within a constructor or a method.

class Student {
   int age;   
   Student(int age) {
      this.age = age;	
   }
}
  • Call one type of constructor (parametrized constructor or default) from other in a class. It is known as explicit constructor invocation.

class Student {
   int age
   Student() {
      this(20);
   }
   
   Student(int age) {
      this.age = age;	
   }
}

Example: Using this Keyword in Java Class Methods

Here is an example that uses this keyword to access the members of a class. Copy and paste the following program in a file with the name, Tester.java.

package com.tutorialspoint;

public class Tester {
   // Instance variable num
   int num = 10;
	
   Tester() {
      System.out.println("This is an example program on keyword this");	
   }

   Tester(int num) {
      // Invoking the default constructor
      this();
      
      // Assigning the local variable num to the instance variable num
      this.num = num;	   
   }
   
   public void greet() {
      System.out.println("Hi Welcome to Tutorialspoint");
   }
      
   public void print() {
      // Local variable num
      int num = 20;
      
      // Printing the local variable
      System.out.println("value of local variable num is : "+num);
      
      // Printing the instance variable
      System.out.println("value of instance variable num is : "+this.num);
      
      // Invoking the greet method of a class
      this.greet();     
   }
   
   public static void main(String[] args) {
      // Instantiating the class
      Tester obj1 = new Tester();
      
      // Invoking the print method
      obj1.print();
	  
      // Passing a new value to the num variable through parametrized constructor
      Tester obj2 = new Tester(30);
      
      // Invoking the print method again
      obj2.print(); 
   }
}

Output

This is an example program on keyword this 
value of local variable num is : 20
value of instance variable num is : 10
Hi Welcome to Tutorialspoint
This is an example program on keyword this 
value of local variable num is : 20
value of instance variable num is : 30
Hi Welcome to Tutorialspoint

Public Vs. Static Class Methods

There are two types of class methods public and static class method. The public class methods are accessed through the objects whereas, the static class methods are accessed are accesses without an object. You can directly access the static methods.

Example

The following example demonstrates the difference between public and static class methods:

public class Main {
  // Creating a static method
  static void fun1() {
    System.out.println("fun1: This is a static method.");
  }

  // Creating a public method
  public void fun2() {
    System.out.println("fun2: This is a public method.");
  }

  // The main() method
  public static void main(String[] args) {
    // Accessing static method through the class
    fun1();

    // Creating an object of the Main class
    Main obj = new Main();
    // Accessing public method through the object
    obj.fun2();
  }
}

Output

fun1: This is a static method.
fun2: This is a public method.

The finalize( ) Method

It is possible to define a method that will be called just before an object's final destruction by the garbage collector. This method is called finalize( ), and it can be used to ensure that an object terminates cleanly.

For example, you might use finalize( ) to make sure that an open file owned by that object is closed.

To add a finalizer to a class, you simply define the finalize( ) method. The Java runtime calls that method whenever it is about to recycle an object of that class.

Inside the finalize( ) method, you will specify those actions that must be performed before an object is destroyed.

The finalize( ) method has this general form −

protected void finalize( ) {
   // finalization code here
}

Here, the keyword protected is a specifier that prevents access to finalize( ) by code defined outside its class.

This means that you cannot know when or even if finalize( ) will be executed. For example, if your program ends before garbage collection occurs, finalize( ) will not execute.

Tutorix - AI Tutor
Previous Quiz Next
Advertisements
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.