[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:
NickTononi
2019-10-19 22:19:09 +02:00
committed by ashleyfrieze
parent 04dc9ddb41
commit 22deaaa756
4 changed files with 71 additions and 0 deletions

View File

@@ -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() {}
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}

View File

@@ -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();
}
}