Hasta ahora se ha trabajado con una clase simple que contiene el método main(..). En este ejercicio se va a crear varias clases entre las cuales una clase invoca otras clases, más precisamente una clase invoca un método de otra clase.
0. Ejecutar el IDE NetBeans.
1. Crear el proyecto NetBeans.
Figura-1.10: Creación de un nuevo proyecto
public class StudentRecord
{ // Declare instance variables. private String name; private double mathGrade; private double englishGrade; private double scienceGrade; // Declare static variables. private static int studentCount = 0; /** * Returns the name of the student */ public String getName(){ return name; } /** * Changes the name of the student */ public void setName(String temp ){ name =temp; } /** * Computes the average of the english, math and science * grades */ public double getAverage(){ double result =0; result =(getMathGrade()+getEnglishGrade()+getScienceGrade() )/3; return result; } /** * Returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount; } /** * Increases the number of instances of StudentRecords. * This is a static method. */ public static void increaseStudentCount(){ studentCount++; } // Instance methods public double getMathGrade() { return mathGrade; } public void setMathGrade(double mathGrade) { this.mathGrade = mathGrade; } public double getEnglishGrade() { return englishGrade; } public void setEnglishGrade(double englishGrade) { this.englishGrade = englishGrade; } public double getScienceGrade() { return scienceGrade; } public void setScienceGrade(double scienceGrade) { this.scienceGrade = scienceGrade; } } |
public class StudentRecordExample
{ public static void main(String[] args) { // Create an object instance of StudentRecord class. StudentRecord annaRecord =new StudentRecord(); // Increament the studentCount by invoking a static method. StudentRecord.increaseStudentCount(); // Create another object instance of StudentRecord class. StudentRecord beahRecord =new StudentRecord(); // Increament the studentCount by invoking a static method. StudentRecord.increaseStudentCount(); // Create the 3rd object instance of StudentRecord class. StudentRecord crisRecord =new StudentRecord(); // Increament the studentCount by invoking a static method. StudentRecord.increaseStudentCount(); // Set the names of the students. annaRecord.setName("Anna"); beahRecord.setName("Beah"); crisRecord.setName("Cris"); // Print anna's name. System.out.println("Name = " + annaRecord.getName()); // Print number of students. System.out.println("Student Count = "+StudentRecord.getStudentCount()); } } |
Name = Anna Student Count = 3 |
Este ejercicio ha mostrado la forma de crear y usar una clase propia llamada StudentRecord usando la palabra reservada new.
Volver al inicio
1. Creación del proyecto NetBeans
public class Variables
{ // Static variables static int staticintA = 10; static String staticStringB ="I am static string"; // Instance variables int instanceintA = 20; String instanceStringB = "I am instance string"; } |
public class StaticVariablesExample
{ public static void main(String[] args) { // Access static variables of Variables class. // Note that you don't have to create an object instance // of Variables class. System.out.println("Variables.staticintA = " + Variables.staticintA); System.out.println("Variables.staticStringB = " + Variables.staticStringB); Variables.staticStringB = "Life is good!"; System.out.println("Variables.staticStringB = " + Variables.staticStringB); // Access instance variables of Variables class. // Note that you have to create an object instance // of Variables class before you access them. Variables objectInstance1 = new Variables(); Variables objectInstance2 = new Variables(); objectInstance1.instanceintA = 1; System.out.println("objectInstance1.instanceintA = " + objectInstance1.instanceintA); objectInstance2.instanceintA = 3; System.out.println("objectInstance2.instanceintA = " + objectInstance2.instanceintA); // The static variable can be accessed from an object instance. System.out.println("objectInstance1.staticintA = " + objectInstance1.staticintA); objectInstance1.staticintA = 220; System.out.println("objectInstance1.staticintA = " + objectInstance1.staticintA); System.out.println("Variables.staticintA = " + Variables.staticintA); // The static variable can be accessed from multiple object instances. objectInstance2.staticintA = 550; System.out.println("objectInstance1.staticintA = " + objectInstance1.staticintA); System.out.println("objectInstance2.staticintA = " + objectInstance2.staticintA); System.out.println("Variables.staticintA = " + Variables.staticintA); } } |
Variables.staticintA =
10 Variables.staticStringB = I am static string Variables.staticStringB = Life is good! objectInstance1.instanceintA = 1 objectInstance2.instanceintA = 3 objectInstance1.staticintA = 10 objectInstance1.staticintA = 220 Variables.staticintA = 220 objectInstance1.staticintA = 550 objectInstance2.staticintA = 550 Variables.staticintA = 550 |
Variables.instanceintA =
3; |
1. Creación del proyecto NetBeans
public class Methods
{ // Static variable static int a = 0; // Static method static void staticMethod(int i) { System.out.println("staticMethod("+ i +") entered"); } // Anonymous static method. The things inside the anonymous // static method get executed when the class is loaded. static { //static block System.out.println("Anonymous static method entered, a = " + a); a += 1; // same thing as a = a + 1 System.out.println("Anonymous static method exiting, a = " + a); } // Non-static method void myNonStaticMethods(int i){ System.out.println("myNonStaticMethod("+ i +") entered"); } } |
public class StaticMethodsExample
{ public static void main(String[] args) { // Access a static variable of Methods class. Note that you don't have to // create an object instance of Methods class. System.out.println("Methods.a = " + Methods.a); // Invoke a static method of Methods class. Note that you don't have to // create an object instance of Methods class. Methods.staticMethod(5); // The static variable can be accessed from an object instance. Methods d = new Methods(); System.out.println("d.a = " + d.a); // The static method can be invoked from an object instance. d.staticMethod(0); // The same static variable can be accessed from multiple instances. Methods e = new Methods(); System.out.println("e.a = " + e.a); d.a += 3; System.out.println("Methods.a = " + Methods.a); System.out.println("d.a = " + d.a); System.out.println("e.a = " + e.a); } } |
Anonymous static method entered, a =
0 Anonymous static method exiting, a = 1 Methods.a = 1 staticMethod(5) entered d.a = 1 staticMethod(0) entered e.a = 1 Methods.a = 4 d.a = 4 e.a = 4 |
Methods.myNonStaticMethod(3); |
En este ejercicio se ha desarrollado aplicaciones Java
que usan variables y métodos static.
En este ejercicio se revisará el concepto de overloading. Se hace notar que la sobrecarga (overloading) y la sobreescritura (overriding) son dos conceptos diferentes.
public class StudentRecord
{ // Declare instance variables. private String name; private double mathGrade; private double englishGrade; private double scienceGrade; private double average; // Declare static variables. private static int studentCount = 0; /** * Returns the name of the student */ public String getName(){ return name; } /** * Changes the name of the student */ public void setName(String temp ){ name =temp; } /** * Computes the average of the english,math and science * grades */ public double getAverage(){ double result =0; result =(getMathGrade()+getEnglishGrade()+getScienceGrade() )/3; return result; } /** * Returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount; } /** * Increases the number of instances of StudentRecords */ public static void increaseStudentCount(){ studentCount++; } public double getMathGrade() { return mathGrade; } public void setMathGrade(double mathGrade) { this.mathGrade = mathGrade; } public double getEnglishGrade() { return englishGrade; } public void setEnglishGrade(double englishGrade) { this.englishGrade = englishGrade; } public double getScienceGrade() { return scienceGrade; } public void setScienceGrade(double scienceGrade) { this.scienceGrade = scienceGrade; } // Overloaded myprint(..) methods public void myprint(){ System.out.println("First overloaded method: Nothing is passed on"); } public void myprint(String name ){ System.out.println("Second overloaded method: Name:"+name); } public void myprint(String name, double averageGrade){ System.out.print("Third overloaded method: Name:"+name+" "); System.out.println("Average Grade:"+averageGrade); } } |
public class StaticVariablesMethods
{ public static void main(String[] args) { // Create an object instance of StudentRecord class. StudentRecord annaRecord =new StudentRecord(); // Increament the studentCount by invoking a static method. StudentRecord.increaseStudentCount(); // Create another object instance of StudentRecord class. StudentRecord beahRecord =new StudentRecord(); // Increament the studentCount by invoking a static method. StudentRecord.increaseStudentCount(); // Create the 3rd object instance of StudentRecord class. StudentRecord crisRecord =new StudentRecord(); // Increament the studentCount by invoking a static method. StudentRecord.increaseStudentCount(); // Set the names of the students. annaRecord.setName("Anna"); beahRecord.setName("Beah"); crisRecord.setName("Cris"); // Print anna's name. System.out.println("Name = " + annaRecord.getName()); // Print number of students. System.out.println("Student Count = "+StudentRecord.getStudentCount()); // Set Anna's grades annaRecord.setName("Anna"); annaRecord.setEnglishGrade(95.5); annaRecord.setScienceGrade(100); // Invoke overloaded methods annaRecord.myprint(); annaRecord.myprint(annaRecord.getName()); annaRecord.myprint(annaRecord.getName(), annaRecord.getAverage()); } } |
Name = Anna Student Count = 3 First overloaded method: Nothing is passed on Second overloaded method: Name:Anna Third overloaded method: Name:Anna Average Grade:65.16666666666667 |
Este ejercicio ha mostrado el uso de método sobrecargados.
Este ejercicio muestra el concepto de constructores.
1. Creación del proyecto NetBeans
public class StudentRecord
{ // Declare instance variables. private String name; private double mathGrade; private double englishGrade; private double scienceGrade; private double average; // Declare static variables. private static int studentCount = 0; // Default constructor public StudentRecord() { } // Constructor that gets single parameter public StudentRecord(String name){ this.name = name; } // Constructor that gets two parameters public StudentRecord(String name, double mGrade){ this.name = name; mathGrade = mGrade; } // Constructor that gets three parameters public StudentRecord(String name, double mGrade, double eGrade){ this.name = name; mathGrade = mGrade; englishGrade = eGrade; } // Constructor that gets four parameters public StudentRecord(String name, double mGrade, double eGrade, double sGrade){ this.name = name; mathGrade = mGrade; englishGrade = eGrade; scienceGrade = sGrade; } /** * Returns the name of the student */ public String getName(){ return name; } /** * Changes the name of the student */ public void setName(String temp ){ name =temp; } /** * Computes the average of the english,math and science * grades */ public double getAverage(){ double result =0; result =(getMathGrade()+getEnglishGrade()+getScienceGrade() )/3; return result; } /** * Returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount; } /** * Increases the number of instances of StudentRecords. * This is a static method. */ public static void increaseStudentCount(){ studentCount++; } // Instance methods public double getMathGrade() { return mathGrade; } public void setMathGrade(double mathGrade) { this.mathGrade = mathGrade; } public double getEnglishGrade() { return englishGrade; } public void setEnglishGrade(double englishGrade) { this.englishGrade = englishGrade; } public double getScienceGrade() { return scienceGrade; } public void setScienceGrade(double scienceGrade) { this.scienceGrade = scienceGrade; } } |
3. Modificar ConstructorExample.java como se muestra en Código-4.12.
public class ConstructorExample
{ public static void main(String[] args) { // Create an object instance of StudentRecord class. StudentRecord annaRecord = new StudentRecord("Anna"); // Increament the studentCount by invoking a static method. StudentRecord.increaseStudentCount(); // Create another object instance of StudentRecord class. StudentRecord beahRecord =new StudentRecord("Beah", 45); // Increament the studentCount by invoking a static method. StudentRecord.increaseStudentCount(); // Create the 3rd object instance of StudentRecord class. StudentRecord crisRecord =new StudentRecord("Cris", 23.3, 67.45, 56); // Increament the studentCount by invoking a static method. StudentRecord.increaseStudentCount(); // Print Cris' name and average System.out.println("Name = " + crisRecord.getName() + " Average = " + crisRecord.getAverage()); // Print number of students. System.out.println("Student Count = "+StudentRecord.getStudentCount()); } } |
4. Compilar y ejecutar el programa
Name = Cris Average =
48.916666666666664 Student Count = 3 |
1. Modificar StuentRecord.java como se muestra en Código-4.20.
public class StudentRecord
{ // Declare instance variables. private String name; private double mathGrade; private double englishGrade; private double scienceGrade; private double average; // Declare static variables. private static int studentCount = 0; // Default constructor public StudentRecord() { } // Constructor that gets single parameter public StudentRecord(String name){ this.name = name; } // Constructor that gets two parameters public StudentRecord(String name, double mGrade){ this(name); mathGrade = mGrade; } // Constructor that gets three parameters public StudentRecord(String name, double mGrade, double eGrade){ this(name, mGrade); englishGrade = eGrade; } // Constructor that gets four parameters public StudentRecord(String name, double mGrade, double eGrade, double sGrade){ this(name, mGrade, eGrade); scienceGrade = sGrade; } /** * Returns the name of the student */ public String getName(){ return name; } /** * Changes the name of the student */ public void setName(String temp ){ name =temp; } /** * Computes the average of the english,math and science * grades */ public double getAverage(){ double result =0; result =(getMathGrade()+getEnglishGrade()+getScienceGrade() )/3; return result; } /** * Returns the number of instances of StudentRecords */ public static int getStudentCount(){ return studentCount; } /** * Increases the number of instances of StudentRecords. * This is a static method. */ public static void increaseStudentCount(){ studentCount++; } // Instance methods public double getMathGrade() { return mathGrade; } public void setMathGrade(double mathGrade) { this.mathGrade = mathGrade; } public double getEnglishGrade() { return englishGrade; } public void setEnglishGrade(double englishGrade) { this.englishGrade = englishGrade; } public double getScienceGrade() { return scienceGrade; } public void setScienceGrade(double scienceGrade) { this.scienceGrade = scienceGrade; } } |
2. Compilar y ejecutar el programa
Name = Cris Average =
48.916666666666664 Student Count = 3 |
Este ejercicio, ha mostrado los métodos sobrecargados en una clase y cómo invocar un método sobrecargado en particualr pasando los diferentes conjuntos de parámetros.
Este ejercicio muestra el concepto de la referencia "this".
1. Creación del proyecto NetBeans
public class DummyClass
{ void mymethod1(){ // Note that mymethod2() and this.mymethod2() are the same thing. String s1 = mymethod2("Sang Shin"); String s2 = this.mymethod2("Sang Shin"); System.out.println("s1 = " + s1 + " s2 = " + s2); } String mymethod2(String name){ return "Hello " + name; } } |
public class ThisReferenceExample
{ public static void main(String[] args) { DummyClass d1 = new DummyClass(); d1.mymethod1(); } } |
4. Compilar y ejecutar el programa
s1 = Hello Sang Shin s2 = Hello Sang
Shin |
public class DummyClass { void mymethod1(){ // Note that mymethod2() and this.mymethod2() are the same thing. String s1 = mymethod2("Sang Shin"); String s2 = this.mymethod2("Sang Shin"); System.out.println("s1 = " + s1 + " s2 = " + s2); } String mymethod2(String name){ return "Hello " + name; } // Compile error - you cannot invoke instance method // from a static method. static void mymethod3(){ String s1 = mymethod2("Sang Shin"); String s2 = this.mymethod2("Sang Shin"); System.out.println("s1 = " + s1 + " s2 = " + s2); } } |
public class DummyClass
{ void mymethod1(){ // Note that mymethod2() and this.mymethod2() are the same thing. String s1 = mymethod2("Sang Shin"); String s2 = this.mymethod2("Sang Shin"); System.out.println("s1 = " + s1 + " s2 = " + s2); // Pass the current object instance as a parameter String s3 = this.mymethod3(this); System.out.println("s3 = " + s3); } String mymethod2(String name){ return "Hello " + name; } String mymethod3(Object o1){ return o1.getClass().getName(); } } |
2. Compilar y ejecutar el programa
s1 = Hello Sang Shin s2 = Hello Sang
Shin s3 = DummyClass |
public class DummyClass
{ String hello ="Hello"; String bye = "Bye"; void mymethod1(){ // Note that mymethod2() and this.mymethod2() are the same thing. String s1 = mymethod2("Sang Shin"); String s2 = this.mymethod2("Sang Shin"); System.out.println("s1 = " + s1 + " s2 = " + s2); // Pass the current object instance as a parameter String s3 = this.mymethod3(this, this.hello); System.out.println("s3 = " + s3); s3 = this.mymethod3(this, this.bye); System.out.println("s3 = " + s3); } String mymethod2(String name){ return "Hello " + name; } String mymethod3(Object o1, String s){ return s + " " + o1.getClass().getName(); } } |
4. Compilar y ejecutar el programa
s1 = Hello Sang Shin s2 = Hello Sang
Shin s3 = Hello DummyClass s3 = Bye DummyClass |
Este ejercicio ha mostrado el uso de la referencia "this".
package
myaccessmodifierexampleproject; public class DummyClass { // Private field. Can be accessed only within the // same class. private String s1 = "private string"; // Protected field. Can be accessed only within // the same package. protected String s2 = "protected string"; // Public field. Can be accessed from anybody. public String s3 = "public string"; // Default is protected String s4 = "string without access modifier"; // Private method. Can be accessed only within the // same class. private void method1(){ } // Protected method. Can be accessed only within // the same package. protected void method2(){ } // Public method. Can be accessed from anybody. public void method3(){ } // Default is protected. void method4(){ } } |
package
myaccessmodifierexampleproject; public class Main { public static void main(String[] args) { DummyClass t = new DummyClass(); // Compiler error expected System.out.println("s1 = " + t.s1); // accessing private variable of DummayClass class // No compile error expected System.out.println("s2 = " + t.s2); // accessing protected variable System.out.println("s3 = " + t.s3); // accessing public variable System.out.println("s4 = " + t.s4); // accessing default access modifier variable // Compiler error expected t.method1(); // calling private method of DummyClass class // No compile error expected t.method2(); // calling protected method t.method3(); // calling public method t.method4(); // calling default access modifier method } } |
package mynewpackage; //Import DummyClass import myaccessmodifierexampleproject.DummyClass; public class DummyClass2 { public DummyClass2() { DummyClass t = new DummyClass(); // Compiler error expected System.out.println("s1 = " + t.s1); // accessing private variable of DummayClass class System.out.println("s2 = " + t.s2); // accessing protected variable System.out.println("s4 = " + t.s4); // accessing default access modifier variable t.method1(); // calling private method of DummyClass class t.method2(); // calling protected method t.method4(); // calling default access modifier method // No compile error expected System.out.println("s3 = " + t.s3); // accessing public variable t.method3(); // calling public method } } |
Este ejercicio ha mostrado el uso de modificadores de acceso para restringir los privilegios de acceso entre
clases.