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();
    
        }   
    
    }
    
  • 相关阅读:
    《剑指offer》 面试题43 n个骰子的点数 (java)
    《剑指offer》面试题45 圆圈中最后剩下的数字(Java版本)
    《剑指offer》面试题39 二叉树的深度(java)
    《剑指offer》面试题32----从1到n整数中1出现的次数
    快速排序思路整理
    《Java程序猿面试宝典》之字符串
    Tomcat的server.xml
    easyui combobox 清除选中项目 和 清空option选项
    2019
    throw UnsupportedOperationException
  • 原文地址:https://www.cnblogs.com/seancheer/p/10707992.html
Copyright © 2011-2022 走看看