zoukankan      html  css  js  c++  java
  • Java语法细节

    JAVA访问和修饰符的关系一览表

    Modifier Class Package Subclass World
    public Y Y Y Y
    protected Y Y Y N
    no modifier Y Y N N
    private Y N N N



    • 关于父类覆写以及protected的一些细节:

    package1中的代码:

    MainClass.java

    package org.seancheer.package1;
    
    import org.seancheer.package2.SecondChild;
    
    public class MainClass {
     public static void main(String[] args)
       {
          /*
    
          * 对于没有标识符的方法,默认的是包访问,所以对于SecondChild方法,
    
          * 虽然也有同名的func()方法,但是实际上并没有进行覆写操作,调用的
    
          * 还是父类的方法。
    
          */
    
         ParentClass parentOne = new FirstChild();
    
         parentOne.func();    //func() in first child !
    
         ParentClass parentTwo = new SecondChild();
    
         parentTwo.func();    //func() in the parent class !
    
    
    
         /*
    
          * 注意!!!!和c++不一样的地方,protected修饰符的方法也可被实例访问到,
    
          * 但是必须有个前提:该实例new出来的位置必须和类在同一个package内,在其
    
           * 他package是无法访问到的!
    
          */
    
         ParentClass parent = new ParentClass();
         parent.protectedMethod();
    
      }
    
    }
    

    FirstChild.java

    package org.seancheer.package1;
    public class FirstChild extends ParentClass{
    
        @Override
    
        void func() {
    
           // TODO Auto-generated method stub
    
           System.out.println("func() in first child !");
    
        }
    
    }
    

    ParentClass.java

    package org.seancheer.package1;
    
    public class ParentClass {
    
        void func()
    
        {
    
           System.out.println("func() in the parent class !");
    
        }
    
        protected void protectedMethod() {
    
           System.out.println("protectedMethod() in the parent class !");
    
        }
    
    }
    

    package2中的代码:

    SecondChild.java

    package org.seancheer.package2;
    
    import org.seancheer.package1.ParentClass;
    
    public class SecondChild extends ParentClass{
    
        void func()
    
        {
    
           System.out.println("func() in the second child !");
    
        }
    
       
    
        public static void main(String[] args)
    
        {
    
           ParentClass parent = new ParentClass();
    
          
    
           //注意,是无法访问到protected方法的,但是如果在同一个包内就是可以访问的!
    
           //parent.protectedMethod();
    
        }   
    
    }
    
  • 相关阅读:
    ubuntu给手机建wifi
    ubuntu系统之难
    【百度之星2014~复赛 解题报告~正解】The Query on the Tree
    【百度之星2014~复赛)解题报告】The Query on the Tree
    【百度之星2014~初赛解题报告】
    【百度之星2014~初赛(第二轮)解题报告】JZP Set
    【百度之星2014~资格赛解题报告】
    【百度之星2014~初赛(第二轮)解题报告】Chess
    vi 中插入当前时间
    安装软件时依赖冲突的万能解决方案
  • 原文地址:https://www.cnblogs.com/seancheer/p/10707992.html
Copyright © 2011-2022 走看看