[BAEL-3147] Java 'protected' modifier (#7886)
* [BAEL-3147] Java 'protected' modifier * updated README.md * Update README.md * Update SecondGenericClass.java
This commit is contained in:
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.core.modifiers;
|
||||
|
||||
public class FirstClass {
|
||||
|
||||
protected String name;
|
||||
|
||||
protected FirstClass(String name) {
|
||||
this.name = name;
|
||||
}
|
||||
|
||||
protected String getName() {
|
||||
return name;
|
||||
}
|
||||
|
||||
protected static class InnerClass {
|
||||
public InnerClass() {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.baeldung.core.modifiers;
|
||||
|
||||
public class GenericClass {
|
||||
|
||||
public static void main(String[] args) {
|
||||
// accessing protected constructor
|
||||
FirstClass first = new FirstClass("random name");
|
||||
// using protected method
|
||||
System.out.println("FirstClass name is " + first.getName());
|
||||
// accessing a protected field
|
||||
first.name = "new name";
|
||||
// instantiating protected inner class
|
||||
FirstClass.InnerClass innerClass = new FirstClass.InnerClass();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package com.baeldung.core.modifiers.otherpackage;
|
||||
|
||||
import com.baeldung.core.modifiers.FirstClass;
|
||||
|
||||
public class SecondClass extends FirstClass {
|
||||
|
||||
public SecondClass(String name) {
|
||||
// accessing protected constructor
|
||||
super(name);
|
||||
// using protected method
|
||||
System.out.println("SecondClass name is " + this.getName());
|
||||
// accessing a protected field
|
||||
this.name = "new name";
|
||||
// instantiating protected inner class -> add public constructor to InnerClass
|
||||
FirstClass.InnerClass innerClass = new FirstClass.InnerClass();
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.baeldung.core.modifiers.otherpackage;
|
||||
|
||||
import com.baeldung.core.modifiers.FirstClass;
|
||||
//import com.baeldung.core.modifiers.FirstClass.InnerClass;
|
||||
|
||||
public class SecondGenericClass {
|
||||
|
||||
// uncomment the following lines to see the errors
|
||||
public static void main(String[] args) {
|
||||
// accessing protected constructor
|
||||
// FirstClass first = new FirstClass("random name");
|
||||
// using protected method
|
||||
// System.out.println("FirstClass name is " + first.getName());
|
||||
// accessing a protected field
|
||||
// first.name = "new name";
|
||||
// instantiating protected inner class
|
||||
// FirstClass.InnerClass innerClass = new FirstClass.InnerClass();
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user