Static/Class methods

本文深入探讨了Java编程中实例方法和静态方法的区别、调用方式、使用场景及注意事项,帮助开发者更好地理解和应用这两种方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

There are two types of methods.

  • Instance methods are associated with an object and use the instance variables of that object. This is the default.
  • Static methods use no instance variables of any object of the class they are defined in. If you define a method to be static, you will be given a rude message by the compiler if you try to access any instance variables. You can access static variables, but except for constants, this is unusual. Static methods typically take all they data from parameters and compute something from those parameters, with no reference to variables. This is typical of methods which do some kind of generic calculation. A good example of this are the many utility methods in the predefined Math class. (See Math and java.util.Random).

Qualifying a static call

From outside the defining class, an instance method is called by prefixing it with an object, which is then passed as an implicit parameter to the instance method, eg, inputTF.setText("");

A static method is called by prefixing it with a class name, eg, Math.max(i,j);. Curiously, it can also be qualified with an object, which will be ignored, but the class of the object will be used.

Example

Here is a typical static method.

class MyUtils {
    . . .
    //================================================= mean
    public static double mean(int[] p) {
        int sum = 0;  // sum of all the elements
        for (int i=0; i<p.length; i++) {
            sum += p[i];
        }
        return ((double)sum) / p.length;
    }//endmethod mean
    . . .
}

The only data this method uses or changes is from parameters (or local variables of course).

Why declare a method static

The above mean() method would work just as well if it wasn't declared static, as long as it was called from within the same class. If called from outside the class and it wasn't declared static, it would have to be qualified (uselessly) with an object. Even when used within the class, there are good reasons to define a method as static when it could be.

  • Documentation. Anyone seeing that a method is static will know how to call it (see below). Similarly, any programmer looking at the code will know that a static method can't interact with instance variables, which makes reading and debugging easier.
  • Efficiency. A compiler will usually produce slightly more efficient code because no implicit object parameter has to be passed to the method.

Calling static methods

There are two cases.

Called from within the same class
Just write the static method name. Eg,
// Called from inside the MyUtils class
double avgAtt = mean(attendance);
Called from outside the class
If a method (static or instance) is called from another class, something must be given before the method name to specify the class where the method is defined. For instance methods, this is the object that the method will access. For static methods, the class name should be specified. Eg,
// Called from outside the MyUtils class.
double avgAtt = MyUtils.mean(attendance);
If an object is specified before it, the object value will be ignored and the the class of the object will be used.

Accessing static variables

Altho a static method can't access instance variables, it can access static variables. A common use of static variables is to define "constants". Examples from the Java library are Math.PI or Color.RED. They are qualified with the class name, so you know they are static. Any method, static or not, can access static variables. Instance variables can be accessed only by instance methods.

Alternate call

What's a little peculiar, and not recommended, is that an object of a class may be used instead of the class name to access static methods. This is bad because it creates the impression that some instance variables in the object are used, but this isn't the case.

<template> <view class="detail-container"> <view class="navigation"> <view class="navigation_icon" @click="gotosearch"> <image class="search-icon" src="/static/搜索.png" mode=""></image> </view> </view> <!-- 导航栏 --> <view class="nav-bar"> <view v-for="(category, index) in categories" :key="index" class="nav-item" :class="{ active: currentIndex === index }" @click="selectCategory(index)"> {{ category.name }} </view> </view> <!-- 商品列表 --> <view class="product-list"> <view v-for="(product, index) in currentProducts" :key="index" class="product-item"> <image :src="product.image" class="product-image"></image> <text class="product-name">{{ product.name }}</text> </view> </view> </view> </template> <script> export default { data() { return { // 分类数据 categories: [{ name: "精选推荐", products: [{ name: "商品1", image: "/static/大商品.png" }, { name: "商品2", image: "/static/商品.png" }, { name: "商品3", image: "/static/商品.png" }, { name: "商品4", image: "/static/商品.png" }, { name: "商品5", image: "/static/商品.png" }, { name: "商品6", image: "/static/商品.png" }, { name: "商品7", image: "/static/商品.png" }, { name: "商品8", image: "/static/商品.png" }, { name: "商品9", image: "/static/商品.png" }, { name: "商品10", image: "/static/商品.png" } ] }, { name: "商务文具", products: [{ name: "商品1", image: "/static/大商品.png" }, { name: "商品2", image: "/static/商品.png" }, { name: "商品3", image: "/static/商品.png" }, { name: "商品4", image: "/static/商品.png" }, { name: "商品5", image: "/static/商品.png" }, { name: "商品6", image: "/static/商品.png" }, { name: "商品7", image: "/static/商品.png" }, { name: "商品8", image: "/static/商品.png" }, { name: "商品9", image: "/static/商品.png" }, { name: "商品10", image: "/static/商品.png" } ] }, { name: "家具生活", products: [{ name: "商品1", image: "/static/大商品.png" }, { name: "商品2", image: "/static/商品.png" }, { name: "商品3", image: "/static/商品.png" }, { name: "商品4", image: "/static/商品.png" }, { name: "商品5", image: "/static/商品.png" }, { name: "商品6", image: "/static/商品.png" }, { name: "商品7", image: "/static/商品.png" }, { name: "商品8", image: "/static/商品.png" }, { name: "商品9", image: "/static/商品.png" }, { name: "商品10", image: "/static/商品.png" } ] }, { name: "数码家电", products: [{ name: "商品1", image: "/static/大商品.png" }, { name: "商品2", image: "/static/商品.png" }, { name: "商品3", image: "/static/商品.png" }, { name: "商品4", image: "/static/商品.png" }, { name: "商品5", image: "/static/商品.png" }, { name: "商品6", image: "/static/商品.png" }, { name: "商品7", image: "/static/商品.png" }, { name: "商品8", image: "/static/商品.png" }, { name: "商品9", image: "/static/商品.png" }, { name: "商品10", image: "/static/商品.png" } ] } ], // 当前选中的分类索引 currentIndex: 0, // 当前显示的商品列表 currentProducts:[] } }, methods: { // 跳转到搜索页面 gotosearch() { uni.navigateTo({ url: "/pages/Classification/search" }); }, // 点击分类项 selectCategory(index) { this.currentIndex = index; this.currentProducts = this.categories[index].products; }, onLoad() { // 初始化时加载第一个分类的商品 this.currentProducts = this.categories[0].products; } } } </script> <style> .detail-container { display: flex; flex-direction: column; height: 100vh; .navigation { width: 50%; height: 50px; margin-left: 50%; /* 以上为让搜索框能点击添加样式切勿修改 */ z-index: 999; display: flex; position: fixed; top: 0; background-color: transparent; justify-content: flex-end; /* 让内容靠右 */ align-items: center; padding-right: 20rpx; /* 右侧留出一些空间 */ } .navigation_icon { display: flex; align-items: center; } .search-icon { width: 40rpx; height: 40rpx; } .nav-bar { display: flex; overflow-x: auto; white-space: nowrap; background-color: #f5f5f5; padding: 10rpx 0; position: fixed; /* 固定导航栏 */ top: 50px; /* 避免与搜索栏重叠 */ width: 100%; z-index: 998; .nav-item { margin: 0 20rpx; padding: 10rpx 20rpx; font-size: 28rpx; color: #333; &.active { color: #1aad19; font-weight: bold; } } } } .product-list { display: flex; flex-wrap: wrap; padding: 20rpx; .product-item { width: 50%; box-sizing: border-box; padding: 10rpx; .product-image { width: 100%; height: 200rpx; border-radius: 10rpx; } .product-name { text-align: center; font-size: 24rpx; color: #333; margin-top: 10rpx; } } } </style>为什么上述代码没有默认加载精选推荐的数据
最新发布
05-21
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值