Class and function in java

Java Class Methods

You learned from the Java Methods chapter that methods are declared within a class, and that they are used to perform certain actions:

Example

Create a method named myMethod() in Main:

myMethod() prints a text (the action), when it is called. To call a method, write the method’s name followed by two parentheses () and a semicolon;

Example

Inside main , call myMethod() :

public class Main < static void myMethod() < System.out.println("Hello World!"); >public static void main(String[] args) < myMethod(); >> // Outputs "Hello World!" 

public class MyClass <
static void myMethod(int x) <
System.out.println(x);
>

public static void main(String[] args) myMethod(10);
>
>

Static vs. Public

You will often see Java programs that have either static or public attributes and methods.

In the example above, we created a static method, which means that it can be accessed without creating an object of the class, unlike public , which can only be accessed by objects:

Example

An example to demonstrate the differences between static and public methods:

public class Main < // Static method static void myStaticMethod() < System.out.println("Static methods can be called without creating objects"); >// Public method public void myPublicMethod() < System.out.println("Public methods must be called by creating objects"); >// Main method public static void main(String[] args) < myStaticMethod(); // Call the static method // myPublicMethod(); This would compile an error Main myObj = new Main(); // Create an object of Main myObj.myPublicMethod(); // Call the public method on the object >> 

Note: You will learn more about these keywords (called modifiers) in the Java Modifiers chapter.

Access Methods With an Object

Example

Create a Car object named myCar . Call the fullThrottle() and speed() methods on the myCar object, and run the program:

// Create a Main class public class Main < // Create a fullThrottle() method public void fullThrottle() < System.out.println("The car is going as fast as it can!"); >// Create a speed() method and add a parameter public void speed(int maxSpeed) < System.out.println("Max speed is: " + maxSpeed); >// Inside main, call the methods on the myCar object public static void main(String[] args) < Main myCar = new Main(); // Create a myCar object myCar.fullThrottle(); // Call the fullThrottle() method myCar.speed(200); // Call the speed() method >> // The car is going as fast as it can! // Max speed is: 200 

Example explained

1) We created a custom Main class with the class keyword.

2) We created the fullThrottle() and speed() methods in the Main class.

3) The fullThrottle() method and the speed() method will print out some text, when they are called.

4) The speed() method accepts an int parameter called maxSpeed — we will use this in 8).

5) In order to use the Main class and its methods, we need to create an object of the Main Class.

6) Then, go to the main() method, which you know by now is a built-in Java method that runs your program (any code inside main is executed).

7) By using the new keyword we created an object with the name myCar .

8) Then, we call the fullThrottle() and speed() methods on the myCar object, and run the program using the name of the object ( myCar ), followed by a dot ( . ), followed by the name of the method ( fullThrottle(); and speed(200); ). Notice that we add an int parameter of 200 inside the speed() method.

Remember that..

The dot ( . ) is used to access the object’s attributes and methods.

To call a method in Java, write the method name followed by a set of parentheses (), followed by a semicolon ( ; ).

Читайте также:  Mysql and php downloads

A class must have a matching filename ( Main and Main.java).

Using Multiple Classes

Like we specified in the Classes chapter, it is a good practice to create an object of a class and access it in another class.

Remember that the name of the java file should match the class name. In this example, we have created two files in the same directory:

Main.java

public class Main < public void fullThrottle() < System.out.println("The car is going as fast as it can!"); >public void speed(int maxSpeed) < System.out.println("Max speed is: " + maxSpeed); >> 

Second.java

When both files have been compiled:

Источник

Class and function in java

Here’s a (partial) example class; a List is an ordered collection of items of any type:

 class List < // fields private Object [] items; // store the items in an array private int numItems; // the current # of items in the list // methods // constructor function public List() < items = new Object[10]; numItems = 0; >// AddToEnd: add a given item to the end of the list public void AddToEnd(Object ob) < . >> 


    Object: Object-oriented programming involves inheritance. In Java, all classes (built-in or user-defined) are (implicitly) subclasses of Object. Using an array of Object in the List class allows any kind of Object (an instance of any class) to be stored in the list. However, primitive types (int, char, etc) cannot be stored in the list.

  • Are used to initialize each instance of a class.
  • Have no return type (not even void).
  • Can be overloaded; you can have multiple constructor functions, each with different numbers and/or types of arguments.

Static Fields and Methods

A method should be made static when it does not access any of the non-static fields of the class, and does not call any non-static methods. (In fact, a static method cannot access non-static fields or call non-static methods.) Methods that would be «free» functions in C++ (i.e., not members of any class) should be static methods in Java. Also, methods that are logically associated with a particular class, but that only manipulate the class’s static fields should be static. For example, if we wanted a function to print the current value of the numLists field defined above, that function should be defined as a static method of the List class.

A public static field or method can be accessed from outside the class using either the usual notation:

class-object.field-or-method-name
class-name.field-or-method-name

The preferred way to access a static field or a static method is using the class name (not using a class object). This is because it makes it clear that the field or method being accessed is static.

Final Fields and Methods

private static final int INITIAL_SIZE = 10;
items = new Object[INITIAL_SIZE];

Consider the program defined below.

class Test < static int x; int k; // constructor with 2 args public Test( int n, int m ) < x = n; k = m; >public static void main(String[] args) < Test t1 = new Test(10, 20); Test t2 = new Test(30, 40); System.out.print(t1.x + " "); System.out.print(t1.k + " "); System.out.print(t2.x + " "); System.out.println(t2.k); >>
A. This program must be in a file called Test.java. Compiling will create one new file called Test.class. B. This program can be in any .java file. Compiling will create one new file called Test.class. C. This program must be in a file called Test.java. Compiling will create two new files called Test.class and main.class. D. This program can be in any .java file. Compiling will create two new files called Test.class and main.class.

Question 2: Which of the following correctly describes what happens when the program is compiled and run?

A. There will be a compile-time error because there is no constructor with no arguments. B. There will be a run-time error because there is no constructor with no arguments. C. There will be no errors; the output will be: 10 20 30 40 D. There will be no errors; the output will be: 30 20 30 40 E. There will be no errors; the output will be: 30 40 30 40

Some Useful Built-in Classes

Note: These classes are not really part of the language; they are provided in the package java.lang. You can get more information on-line via the Java Packages page.

String S1 = "hello", // initialize from a string literal S2 = new String("bye"), // use new and the String constructor S3 = new String(S1); // use new and a different constructor
String S1 = "hello" + "bye", S2 = S1 + "!", S3 = S1 + 10; // the int 10 will be converted to a String, // because the other operand of + is a // String

Note: in all of the examples above, a new string is created and the variable (S1, S2, or S3) is set to point to that new string. For example, the expression S1 + «!» does not change what S1 points to, it creates a new string that contains «hellobye!».

int length() // Note: different from arrays, which just use // length without parens char charAt(int k) // return the kth character in the string, starting // with 0 // runtime error if k < 0 or k >= length() int compareTo(String S) // compare this string with string S // return: // 0 if they are the same // a positive int if this string is greater // a negative int if this string is less boolean equals(Object S) // return true if S is a non-null String that // contains the same characters as this String String substring( -- several forms -- ) // see documentation toLowerCase() toUpperCase() Lots more -- see documentation!

Boolean, Integer, Double, etc


    One such class for each primitive type.

List L = new List(); L.AddToEnd( 10 );

You get a compile-time error saying that type int cannot be converted to type Object. That’s because the AddToEnd method takes an Object as its parameter, and a primitive type like int is not an Object. You can fix this using:

This creates a new Integer object, with the value 10, and passes that object to the AddToEnd method. Note that if you want to retrieve a particular kind of object from a list, you must use a cast. For example, assume that the List class also includes methods to allow a user of the class to iterate through the items in a list; i.e., we think of every list as having a «current pointer», and methods are provided to get the current item, and to move the current pointer:

public void firstElement() // set the current pointer to point to the // first item on the list public Object NextElement() // return the item pointed to by the current // pointer; also advance the current pointer public boolean hasMoreElements() // true iff the current pointer has // not fallen off the end of the list
L.AddToEnd( new Integer( 10 ) ); L.firstElement(); Integer K = L.nextElement();

you’ll get a compile-time error saying that you must use an explicit cast to convert an Object to an Integer. That’s because the return type of nextElement is Object, and you’re trying to assign that into variable K, which is an Integer. Here’s what you need to do:

Integer K = (Integer)L.nextElement();
Integer K = new Integer( 10 ); int x = K.intValue(); Boolean B = new Boolean( true ); boolean b = B.boolValue();

Question 1: Consider the following program.

Solutions to Self-Study Questions


Test Yourself #1

Question 1: B. This program can be in any .java file. Compiling will create one new file called Test.class. (It does not have to be in Test.java, because class Test is not public. No file "main.class" is created, because main is a method, not a class.) Question 2: D. There will be no errors; the output will be: 30 20 30 40 (There is no need for a constructor with no arguments because there are no uses of "new Test" with no arguments.)

Test Yourself #2

Question 1: Why does this program produce the output n = 5; m = 6? In Java, all parameters are passed by value, so changes to the parameters themselves in the function do not affect the values that were passed. The Swap function changes its parameters, j and k, making them point to new Integers, but that has no effect on the values that were passed (variables n and m). Question 2: static String Reverse(String S) < String newS = ""; char c = S[0]; // can't index Strings in Java while (c) < // not a boolean loop condition // (but this would work in C/C++) newS = c + newS; c++; // this doesn't help fetch the next char in S // (increments ascii value of c) >return newS; > Correct version: static String Reverse(String S) < String newS = ""; for (int i=0; ireturn newS; >

Источник

Functions in java

The goal of every programmer is to save time in both programming and debugging. However, there comes a time when you write hundreds of lines of code. It’s very frustrating having to repeat the same code now and then. It is more frustrating when your code gets some error, and you will need to debug the whole program.

Improve your programming expertise by using functions. Functions help in avoiding ambiguity. You will agree that breaking down the code into smaller chunks in functions will help you organize your work, and debugging becomes easy. Why repeat the same lines of code several places where you can put it inside a function and call it whenever you need to perform that task. Code reusability saves a lot of time.

In this tutorial, we will spare some time and discuss functions. In java, a method is the same as a function. All the functions must be defined within a class. By that, we can summarize by defining a Java method as a function belonging to a class. A function is a named unit of code that can be invoked anywhere in the class.

Syntax of a function

Public static void myFuction(String name, int age ) < // fuction code >
  • Access specifier – this shows the scope of availability of a fuction. ‘Public’ means that the function can be called from aywhere in the program. We have other access specifiers such as private and protected.Protected, the method can only be called within the class and its subslcasses. Private can oly be called inside the class
  • Modifier – ‘static’ is optional in a fuction defination. In this case static means the function is a not an object of the main class but a method that belongs to the main class.
  • Retur type – We have functions that return a value and functions that do not return anything. Void, means that the function does not have a return value. If the fuction was to return a value, replace void with the data type of the returned value.
  • Function name – This the name of the function
  • Parameter list – it informs the compiler about the data type it will receive and the value to be returned.

Advantages of functions in Java

  1. Reusability of code – functions help in removing repetition of code in a program. With functions you can define it once and call it anywhere in the program to perform the task you need and you are not limited to the number of times you call the function. Lastly it’s simple to relace the functions into libraries. This allows them to be used by more than one program.

2. Divide and conquer – Using functions helps break a program into smaller manageable chunks, hence making debugging and testing easier. Functions help in collaboration by breaking up the work into tasks for team development.

Источник

Оцените статью