Java Programming For Beginners

Page 1

Java Programming For Beginners

How does a java class access another java class? This is a very interesting topic to talk about for Java Beginners. You have two classes in same folder as well the same class is using the classes from the library.

How is that happening? Let say we have a folder by name class access and it have the described classes

Radio.java

class Radio { Radio() { System.out.println("I am a Radio"); }


}

Car.java

class Car { Radio r; int tyres=4;

Car() { System.out.println("I am a Car:"); System.out.println("I have "+tyres+" tyres"); new Radio(); } public static void main(String[] args) { new Car(); } }

If observed properly, class Car is using the class Radio which is in the same folder as well as class System which is Java library.


How a compiler does discovers the class in folders as well as class in library? Rule is very simple, whenever a compiler encounters


- So whenever a class is accessed in some other file, the discussed rules are followed.

So if the class is in the same folder it is found first, if not found it tries to search it in java.lang package, if not found in java.lang it tries to find some import statements and and try to search in the imported package. Never give your class a name similar to those of the class in Java library. Imagine you write a class and name it as String. Later you write another class which is trying to access class String of java.lang package,

What will happen? The other class wont be able to access java.lang.String as whenever compiler is trying to access String , it finds it in the same folder hence, it never goes to the second option of finding it in java.lang. Is there any way out? - Yes, when the class String is supposed to be accessed in another class it should be used with qualified import, i.e. java.lang.String s="Tom"; If done by this way, compiler never goes through the rule, it searches it directly in the package specified. For the next Topic keep visiting Asterix Solution ( www.asterixsolution.com/java-for-beginner.html ). Asterix Solution is Brand for Professional IT Training Institute. We have experienced professionals of Java Programming For Beginners [ Source : http://www.javawithz.in/2015/07/how-does-java-class-access-another-java.html ]


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.