Using methods to access classes and the instantiate them

Active3 hr before
Viewed126 times

10 Answers


In this section, we discuss the use of the static keyword to create fields and methods that belong to the class, rather than to an instance of the class.,The Java programming language supports static methods as well as static variables. Static methods, which have the static modifier in their declarations, should be invoked with the class name, without the need for creating an instance of the class, as in,A common use for static methods is to access static fields. For example, we could add a static method to the Bicycle class to access the numberOfBicycles static field:,Class methods cannot access instance variables or instance methods directly—they must use an object reference. Also, class methods cannot use the this keyword as there is no instance for this to refer to.

public class Bicycle {

   private int cadence;
   private int gear;
   private int speed;

   // add an instance variable for the object ID
   private int id;

   // add a class variable for the
   // number of Bicycle objects instantiated
   private static int numberOfBicycles = 0;
load more v

The code sample use System's getProperty method to search the properties database for the property called "" System Properties later in this lesson talks more about system properties and the getProperty method. , To use a class variable, you use it directly from the name of the class using Java's dot (.) notation. For example, to reference the System's class variable out, you append the variable name to the class name separated by a period, like this: , All of System's variables and methods are class variables and class methods--they are declared static. For a complete discussion about class variables and class methods and how they differ from instance variables and instance methods, refer to Understanding Instance and Class Members in the Objects, Classes, and Interfaces lesson. , The code sample also uses System.out, a PrintStream that implements the standard output stream. The println method prints its argument to the standard output stream. The next page of this lesson discusses the standard output stream and the other two standard I/O streams provided by the System class.

load more v

5) In order to use the Main class and its methods, we need to create an object of the Main Class.,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:,An example to demonstrate the differences between static and public methods:,2) We created the fullThrottle() and speed() methods in the Main class.

Create a method named myMethod() in Main:

public class Main {
   static void myMethod() {
      System.out.println("Hello World!");
load more v

Using new keyword: It is the most common and general way to create object in java. Example:,There are four ways to create objects in java.Strictly speaking there is only one way(by using new keyword),and the rest internally use new keyword. ,Using clone() method: clone() method is present in Object class. It creates and returns a copy of the object.,Example of an object: dog

As we declare variables like (type name;). This notifies the compiler that we will use name to refer to data whose type is type. With a primitive variable, this declaration also reserves the proper amount of memory for the variable. So for reference variable, type must be strictly a concrete class name. In general, we can’t create objects of an abstract class or an interface.  

Dog tuffy;


Hi my name is tuffy.
My breed, age and color are papillon, 5, white
  • This class contains a single constructor. We can recognize a constructor because its declaration uses the same name as the class and it has no return type. The Java compiler differentiates the constructors based on the number and the type of the arguments. The constructor in the Dog class takes four arguments. The following statement provides “tuffy”,”papillon”,5,”white” as values for those arguments:
Dog tuffy = new Dog("tuffy", "papillon", 5, "white");
  • Using new keyword: It is the most common and general way to create object in java. Example:
// creating object of class Test
Test t = new Test();
  • Using Class.forName(String className) method: There is a pre-defined class in java.lang package with name Class. The forName(String className) method returns the Class object associated with the class with the given string name.We have to give the fully qualified name for a class. On calling new Instance() method on this Class object returns new instance of the class with the given string name.
// creating object of public class Test
// consider class Test present in com.p1 package
Test obj = (Test) Class.forName("com.p1.Test").newInstance();
  • Using clone() method: clone() method is present in Object class. It creates and returns a copy of the object.
        // creating object of class Test
        Test t1 = new Test();

        // creating clone of above object
        Test t2 = (Test) t1.clone();
            FileInputStream file = new FileInputStream(filename);
            ObjectInputStream in = new ObjectInputStream(file);
            Object obj = in .readObject();
  • In real-time, we need different objects of a class in different methods. Creating a number of references for storing them is not a good practice and therefore we declare a static reference variable and use it whenever required. In this case, wastage of memory is less. The objects that are not referenced anymore will be destroyed by Garbage Collector of java. Example:
          Test test = new Test();
          test = new Test();
  • In inheritance system, we use parent class reference variable to store a sub-class object. In this case, we can switch into different subclass objects using same referenced variable. Example:
class Animal {}

class Dog extends Animal {}
class Cat extends Animal {}

public class Test {
   // using Dog object
   Animal obj = new Dog();

   // using Cat object
   obj = new Cat();
  • They are used for immediate method calling.
  • They will be destroyed after method calling.
  • They are widely used in different libraries. For example, in AWT libraries, they are used to perform some action on capturing an event(eg a key press).
  • In the example below, when a key is button(referred by the btn) is pressed, we are simply creating anonymous object of EventHandler class for just calling handle method.
btn.setOnAction(new EventHandler() {
   public void handle(ActionEvent event) {
      System.out.println("Hello World!");
load more v

Create two new Dog objects, and assign them to the first two array elements.,The Dog class has an instance variable size, that the bark() method uses to decide what kind of bark sound to make.,Create two new Dog objects, and assign them to the first two array elements.pets[0] = new Dog(); pets[1] = new Dog();,Methods can use instance variables so that objects of the same type can behave differently.

void play() {
Song t2 = new Song();
Song s3 = new Song();
s3.setArtist("Sex Pistols");
s3.setTitle("My Way");
load more v

So, I am wondering if it is possible to call a method of a class without a creation of an instance of the class.,1) YES, you can use the methods of a class without creating an instance or object of that class through the use of the Keyword "Static".,I have a class with several methods and there is no constructor among these methods.,I have a class with several methods and there is no constructor among these methods.

2) If you declare the method as "Static" then you can call this method by :

                * ClassName.MethodName() *

3) E.g.

class Hello {

   public static void print() {



class MainMethod {
   public static void main(String args[]) {
      // calling static method
load more v

Similarly, when declaring a method, you can specify that method to be a class method rather than an instance method. Class methods can only operate on class variables and cannot access the instance variables defined in the class. , By default, unless otherwise specified, a member declared within a class is an instance member. The class defined below has one instance variable--an integer named x--and two instance methods--x() and setX()--that let other objects set and query the value of x: , To specify that a method is a class method, use the static keyword in the method declaration. Let's change the AnIntegerNamedX class such that its member variable x is once again an instance variable, and its two methods are now class methods: , You use class variables for items that you need only one copy of and which must be accessible by all objects inheriting from the class in which the variable is declared. For example, class variables are often used with final to define constants (this is more memory efficient as constants can't change so you really only need one copy).

class MyClass {
   float aFloat;
load more v

A constructor can use the super keyword to call the constructor of the super class.,If there is a constructor present in the subclass, it needs to first call super() before using "this"., The super keyword is used to call corresponding methods of super class. This is one advantage over prototype-based inheritance. ,As seen above, the fields can be declared with or without a default value.

class Rectangle {
   constructor(height, width) {
      this.height = height;
      this.width = width;
load more v

If the same attribute name occurs in both an instance and in a class, then attribute lookup prioritizes the instance:,Class objects support two kinds of operations: attribute references and instantiation.,Generally speaking, instance variables are for data unique to each instance and class variables are for attributes and methods shared by all instances of the class:,Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by its class) for modifying its state.

def scope_test():
   def do_local():
   spam = "local spam"

def do_nonlocal():
   nonlocal spam
spam = "nonlocal spam"

def do_global():
   global spam
spam = "global spam"

spam = "test spam"
print("After local assignment:", spam)
print("After nonlocal assignment:", spam)
print("After global assignment:", spam)

print("In global scope:", spam)
load more v

The following program shows how to access the private members of a class using inner class.,Following is the program to create an inner class and access it. In the given example, we make the inner class private and access the class through a method.,The following program shows how to pass an anonymous inner class as a method argument.,In Java, just like methods, variables of a class too can have another class as its member. Writing a class within another is allowed in Java. The class written within is called the nested class, and the class that holds the inner class is called the outer class.

Following is the syntax to write a nested class. Here, the class Outer_Demo is the outer class and the class Inner_Demo is the nested class.

class Outer_Demo {
   class Inner_Demo {}
load more v

Other "methods-access" queries related to "Using methods to access classes and the instantiate them"