RUVIDEO
Поделитесь видео 🙏

java 33 | Creating package in java | How to add a class in java package смотреть онлайн

📁 Лайфстайл 👁️ 17 📅 05.12.2023

In last lecture we have seen packages.
A package in Java is used to group related classes. Think of it as a folder in a file directory.
Packages are divided into two categories:
Built-in Packages (packages from the Java API)
User-defined Packages (create your own packages)
To use a class or a package from the library, you need to use the import keyword:

In this lecture we are going to create and use our own packages.
At the end of this lecture students will be able to
Create their own packages
Use the user defined packages
Add the classes in the packages
creating package
First we create a directory myPackage (name should be same as the name of the package).
Then create the MyClass inside the directory with the first statement being the package names.
To compile the Java programs with package statements, you have to use -d option as shown below.
javac -d Destination_folder file_name.java
example
package myPackage;
public class MyClass
{
public void getNames(String s)
{
System.out.println(s);
}
}
Now a package named myPackage is created
And a MyClass.class file is added in this package
if a class wants to use another class in the same package, the package name need not be used.
Classes in the same package find each other without any special syntax.
public class Boss {
public void payEmployee(Employee e)
{ e.mailCheck(); }
}
Here Boss and Employee classes are in same package
What happens if the Employee and Boss classes are not in the same package?
The Boss class must then use one of the following techniques for referring to a class in a different package.
The fully qualified name of the class can be used.
For example −
payroll.Employee

import keyword
The package can be imported using the import keyword and the wild card (*).
For example −
import payroll.*;
The class itself can be imported using the import keyword.
For example −
import payroll.Employee;
A class file can contain any number of import statements.
The import statements must appear after the package statement and before the class declaration.

example
we can use the MyClass class in our program
import myPackage.MyClass;
public class PrintName
{
public static void main(String args[])
{
String name = “use of package demonstration";

MyClass obj = new MyClass();

obj.getNames(name);
}
}
OUTPUT :- use of package demonstration

adding a class in package
We can add more classes to a created package by using package name at the top of the program and saving it in the package directory.
We need a new java file to define a public class, otherwise we can add the new class to an existing .java file and recompile it.
package myPackage;
public class A{
}
Save it by A.java
sub package
 Packages that are inside another package are the  sub packages.
These are not imported by default, they have to imported explicitly.
Also, members of a subpackage have no access privileges, i.e., they are considered as different package for protected and default access specifiers.Example :
import java.util.*;
util is a subpackage created inside java package.

naming convention
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Packages in the Java language itself begin with java. or javax.
Companies use their reversed Internet domain name to begin their package names—
for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
hiding class
When we import a package within a program, only the classes declared as public in that package will be made accessible within this program.
In other words, the classes not declared as public in that package will not be accessible within this program.
We shall profitably make use of the above fact.
When we do so, those classes will be hidden from being accessed by the importing class. 

example
package myPack:
public class VisibleClass{
public void display () {
System.out.println(“Visible to others”);
}
}
class HiddenClass{
void display ();
{ System.out.println(“Hidden to others”);}
}
}
import myPack.*
class Test {
public static void main(String args[])
{
HiddenClass obj = new HiddenClass();
}
}
summary
In this lecture we have covered how to create packages
To access classes of any package we need to use import if the classes are not in the same directory
To add a class in existing packages we have to create a java file with name of the class
A package name should start with lower case letter
If we don’t make a class public inside the package than that class will be hidden from the classes outside the packages
Assignment
Write a java program to make your own package and have some classes in it.
Write another program to make use of the classes which you have put in the above package.

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «java 33 | Creating package in java | How to add a class in java package» бесплатно и без регистрации, вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.