静态方法和静态变量,糟糕的设计实践? [英] Static Methods and static variables, bad design practise?

查看:97
本文介绍了静态方法和静态变量,糟糕的设计实践?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

为什么静态变量被认为是邪恶的?


拥有几年前我在大学学习过面向对象的编程和设计,我记得讲师对使用静态变量或静态方法的人非常生气,因为他们描述的静态是一个非常糟糕的设计。



我的理解是这个
类似静态的东西,是获得全球愿景的东西,即任何东西都可以访问它。



我的理解是否正确?是否存在使用静电的信息?有没有办法避免在代码中使用静态变量或方法?



btw,我知道main方法的静态是成功的先决条件应用程序的操作。

解决方案

static主要用于访问类成员而不创建类实例。如您所知,为什么我们编写 public static void main()只是在运行时bcoz jvm可以访问此方法而无需创建类对象并启动程序。 / p>

根据您的要求,您使用或说如何使用访问说明符声明类成员作为私有,公共,默认和保护访问级别,而静态是将其设置为具有访问级别的静态。



如果没有静态,您必须将您的成员声明为公共成员,或者如果您继承了您的类,则也将其视为受保护。就像在同一个包中一样,你定义了类,然后只是静态继承类。对于没有inhert类的使用,你需要创建该类的对象然后你可以访问那些成员(注意它基于访问说明符)



这里是下面的链接更多细节



http:// xahlee.info/java-a-day/access_specifiers.html



http://www.javabeginner.com/learn-java/introduction-to-java-access-modifiers


Possible Duplicate:
Why are static variables considered evil?

Having studied Object oriented programming and design in college a few years back, i remember lecturers getting pretty angry at people using static variables or static methods, as they describe static to be of a very bad design.

My understanding is this Something of type static, is something that gains global "vision" i.e. it can be accessed by anything.

Is my understanding correct? is there information about the use of static that makes it bad use? and is there a way to avoid using static variables or methods in your code?

btw, i am aware that static for the main method is a pre-requisite to the successful operation of the application.

解决方案

static mainly used for to accessing class members without creating class instance. As you know that why we are writing public static void main() just bcoz at the run time jvm can access this method without creating the class object and start up your program.

Its depending on your requirement that how you used or say how to declaring member of class using access specifier as private, public, default and protect for access level while the static was for make that as static with access level.

Without static you must declare your member as public or if you inherit your class then make as protected also. As in the same package you define the class then just static for inheriting the class. And for using without inhert class you need to create object of that class and then you can access there members (Note it based on access specifier)

here is the link below for more detail

http://xahlee.info/java-a-day/access_specifiers.html

http://www.javabeginner.com/learn-java/introduction-to-java-access-modifiers

这篇关于静态方法和静态变量,糟糕的设计实践?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆