Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Some classes need initialization and some don't

I already tried to search for an answer on the "using the new keyword" but didn't found an answer on my specific question.

Why do some classes have to be created with the keyword new and some don't

For example :

import java.io.BufferedReader

If you want to use this you have to create a new instance

BufferedReader read = new BufferedReader (..............)

But for example with system.console which also needs an import java.io.console. when you want to use this you can just type Console c = system.console()

i'm a beginner in Java and OO programming and found a couple of this examples troughout my book.

Thx for the help

like image 865
Lordeos Avatar asked Jan 01 '26 02:01

Lordeos


1 Answers

In java, fields(aka Attributes) are always associated to either instance or to class.

There could be many instances of a class and to create instance you have to use new operator. To access instance related attributes, you will need to create one and this will be accessed as

ClassName instanceName = new ClassName(); 
instanceName.methorOrAttributeNameGoesHere

For class associated attribute aka Static attribute can be direcly accessed as ClassName.methorOrAttributeNameGoesHere

These are very basics of Java and probably you should first read some good book on Java and OOP like 'Head First Java'

like image 143
Pranalee Avatar answered Jan 02 '26 14:01

Pranalee