1. Examples of getting Started
PackageJihite; Public classdog{intDogage; PublicDog (String name) {System.out.println ("Passed Name is:" +name); } Public voidSetage (intAge ) {Dogage=Age ; } Public intGetage () {System.out.println ("Dog's age is:" +dogage); returnDogage; } Public Static voidMain (String []args) {//Create object (call constructor)Dog Mydog =NewDog ("Haba"); //set age by MethodMydog.setage (3); //get Age by MethodMydog.getage (); //get age by accessing member variablesSystem.out.println ("Dog ' s Age is:" +mydog.dogage); }}
Source file claim rules
A source file has only one public class and can have multiple non-public classes
The name of the source file should be consistent with the name of the public class, for example, in this case the public class is named Dog, then the source file name must be Dog.java
If a class is defined in a package, then the packages statement should be in the first line of the source file, as in this case, in the class Jihite package, then start with the packages Jihite
If the source file contains an import statement, it should be placed between the package statement and the class definition, if there is no package statement, before the class
The import statement and the Packa statement are valid for all classes in the source file and cannot be declared in the same file for different classes of packages
2. Two source files
Employee.java
Packageimport_test; Public classEmployee {String name; intAge ; String designation; Doublesalary; PublicEmployee (String name) { This. Name =name; } Public voidEmpage (intempage) { Age=Empage; } Public voidempdesignation (String empdeg) {designation=empdeg; } Public voidEmpsalary (Doubleempsalary) {Salary=empsalary; } Public voidPrintemployee () {System.out.println ("Name:" +name); System.out.println ("Age:" +Age ); System.out.println ("Designation:" +designation); System.out.println ("Salary:" +salary); }}
The program starts with the main method. In order to run this program, you must include the main method and create an instance object. An instance of 2 classes is instantiated in the following example.
Testemployee.java
Packageimport_test; Public classTestemployee { Public Static voidMain (String args[]) {Employee Empone=NewEmployee ("David"); Employee Emptwo=NewEmployee ("Hamimi"); Empone.empage (26); Empone.empdesignation ("DE"); Empone.empsalary (20000); Empone.printemployee (); Empone.empage (24); Empone.empdesignation ("QA"); Empone.empsalary (15000); Empone.printemployee (); }}
Execution results
name:davidage:designation:desalary:20000.0name:davidage:designation: Qasalary:15000.0
Java Learning--objects and classes