They say in java “every thing is an object”. Is th

2019-02-03 16:53发布

When I type

int a = 5;

Is a an object ?

Can anyone explain to me how in java every thing is an object?

标签: java oop
10条回答
forever°为你锁心
2楼-- · 2019-02-03 17:11

They are wrong. a is not an Object.

查看更多
该账号已被封号
3楼-- · 2019-02-03 17:14

In java you have the primitive types (int, boolean, char, byte...), and everything else extends the Object class and therefore is an object.

But the everything is an object thing mostly means that you can't have code outside of an object class. You can' make script files for examples, it has to be wrapped in a class.

查看更多
Juvenile、少年°
4楼-- · 2019-02-03 17:16

This is not true in java. For example the int is actually a primitive. In java everything is an Object what extends Object. Everything else is not.

So, for example you can't manipulate namespaces (packages in java terms) like objects but in Erlang or Clojure you can.

Although java provides an autoboxing feature which can translate primitives to objects. In your case if you say

Integer a = 5;

java boxes the 5 into the Integer reference. If you want to read about autoboxing click here: autoboxing docs. Objects in java: Objects

If you are looking for a language where everything is an object technically, you can try out Common Lisp for example. In Lisp even the T (stands for boolean true) is an object.

查看更多
We Are One
5楼-- · 2019-02-03 17:16

a here is a primitive. Java has both primitives and objects.

查看更多
Anthone
6楼-- · 2019-02-03 17:20

Although a is not an object but a value of a primitive type, Java makes every attempt to hide this fact from you. Starting with Java 5, primitives are automatically converted to their corresponding object wrappers when necessary, so that you could store them in containers, pass them to methods requiring objects, and so on.

查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-02-03 17:22

Every object is a java.lang.Object Note: java.lang.Object has no super class. ;)

However there are many things which are not Objects.

  • primitives and references.
  • fields (the fields themselves not the contents)
  • local variables and parameters.
  • generic classes (that may change in Java 8)
  • methods (that will change in Java 8)
  • blocks of code (that will change in Java 8)

Having a block of code as an object is one of the most exciting features in Java 8. The following examples will all be Closures and therefor objects.

x => x + 1
(x) => x + 1
(int x) => x + 1
(int x, int y) => x + y
(x, y) => x + y
(x, y) => { System.out.printf("%d + %d = %d%n", x, y, x+y); }
() => { System.out.println("I am a Runnable"); }

e.g. the block of code here will be passed as a Runnable Object

new Thread(() => { System.out.println("I am a Runnable"); }).start();

http://mail.openjdk.java.net/pipermail/lambda-dev/2011-September/003936.html

查看更多
登录 后发表回答