java - Protected access modifier use on Class's Constructor -
i clear using private, default , public access modifiers on public class's constructor.
if constructor private, class object can created in class only.
if constructor default, class object can created in package's classes only.
if constructor public, class object can created in class.
i not clear protected constructor. example:
default constructor
package com.test; public class practiceparent { practiceparent(){ //constructor default access modifier system.out.println("practiceparent default constructor"); } } package com.moretest; import com.test.practiceparent; public class test extends practiceparent { //error. implicit super constructor practiceparent() not visible default constructor. must define explicit constructor public static void main(string[] args) { practiceparent pp=new practiceparent(); //error. constructor practiceparent() not visible } }
i understand these errors. since parentpractice class in other package , constructor default, not visible test class default constructor call super() implicitly. also, object can't created due non visibility of constructor.
protected constructor
but class test extending parentpractice , parentpractice having protected constructor, there no first error i.e. error in calling super() implicitly test's default constructor. implicit super constructor practiceparent() visible test's default constructor practiceparent object can not created. error shown constructor practiceparent() not visible.
package com.test; public class practiceparent { protected practiceparent(){ //constructor protected access modifier system.out.println("practiceparent default constructor"); } } package com.moretest; import com.test.practiceparent; public class test extends practiceparent { //no error public static void main(string[] args) { practiceparent pp=new practiceparent(); //error. constructor practiceparent() not visible /*test t=new test(); outputs "practiceparent default constructor"*/ } }
why super() called not possible create new practiceparent object?
public class test extends practiceparent { //no error public static void main(string[] args) { practiceparent pp=new practiceparent(); //error. constructor practiceparent() not visible test t=new test(); //outputs "practiceparent default constructor" } }
what here have test
extend practiceparent
, meaning test
itself can use protected constructor, because inherits it.
practiceparent pp=new practiceparent(); //error. constructor
this regular instantiation , still uses, or, tries use public constructor, doesn't exist. produce same effect/result if had called anywhere else in application.
Comments
Post a Comment